[英]Delphi FireMonkey TListBox AddObject exception on Android
我在添加一個問題TObject
值到FireMonkey TListBox
德爾福10.0西雅圖。
將Integer
變量強制轉換為TObject
指針時,會引發一種理解。
我嘗試將演員表轉換為TFmxObject
,但沒有成功。 在Windows上,強制轉換的工作方式像一個超級按鈕,但在Android上,它引發了異常。
這是我的代碼:
var
jValue:TJSONValue;
i,total,id: integer;
date: string;
begin
while (i < total) do
begin
date := converteDate(jValue.GetValue('date' + IntToStr(i), ''));
id := StrToInt(jValue.GetValue('id' + IntToStr(i), ''));
ListBox1.Items.AddObject(date, TObject(id));
i := i + 1;
end;
end;
問題在於,在iOS和Android(以及不久的Linux)上, TObject
使用自動引用計數進行生命周期管理,因此,您不能像在Windows和OSX上那樣使用不使用ARC的類型將整數值作為類型的TObject
指針進行類型轉換。 。 在ARC系統上, TObject
指針必須指向實際對象,因為編譯器將對它們執行引用計數語義。 這就是為什么您要例外。
要執行您要嘗試的操作,您必須將整數值包裝在ARC系統上的實對象內部,例如:
{$IFDEF AUTOREFCOUNT}
type
TIntegerWrapper = class
public
Value: Integer;
constructor Create(AValue: Integer);
end;
constructor TIntegerWrapper.Create(AValue: Integer);
begin
inherited Create;
Value := AValue;
end;
{$ENDIF}
...
ListBox1.Items.AddObject(date, {$IFDEF AUTOREFCOUNT}TIntegerWrapper.Create(id){$ELSE}TObject(id){$ENDIF});
...
{$IFDEF AUTOREFCOUNT}
id := TIntegerWrapper(ListBox1.Items.Objects[index]).Value;
{$ELSE}
id := Integer(ListBox1.Items.Objects[index]);
{$ENDIF}
否則,將整數存儲在單獨的列表中,然后在需要時使用TListBox
項的索引作為該列表的索引,例如:
uses
.., System.Generics.Collections;
private
IDs: TList<Integer>;
...
var
...
Index: Integer;
begin
...
Index := IDs.Add(id);
try
ListBox1.Items.Add(date);
except
IDs.Delete(Index);
raise;
end;
...
end;
...
Index := ListBox1.Items.IndexOf('some string');
id := IDs[Index];
它可以移植到所有平台,而不必使用IFDEF
或擔心ARC。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.