问题在于,在 iOS 和 Android(以及很快的 Linux)上,TObject
使用自动引用计数进行生命周期管理,因此您不能TObject
像在不使用 ARC 的 Windows 和 OSX 上那样将整数值类型转换为指针。在 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
s 或担心 ARC。