Android上的Delphi FireMonkey TListBox AddObject异常

时间:2017-03-09 19:06:10

标签: android delphi listbox firemonkey tobject

我在Delphi 10.0 Seattle中向FireMonkey TObject添加TListBox值时遇到问题。

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;

1 个答案:

答案 0 :(得分:5)

问题是在iOS和Android(很快就是Linux)上,TObject使用Automatic Reference Counting进行生命周期管理,因此您不能将整数值类型转换为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或担心ARC。