【问题标题】:Delphi FireMonkey TListBox AddObject exception on AndroidAndroid上的Delphi FireMonkey TListBox AddObject异常
【发布时间】:2017-07-30 22:03:47
【问题描述】:

我在 Delphi 10.0 Seattle 中将 TObject 值添加到 FireMonkey 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;

【问题讨论】:

    标签: android delphi listbox firemonkey tobject


    【解决方案1】:

    问题在于,在 iOS 和 Android(以及很快的 Linux)上,TObject 使用 Automatic Reference Counting 进行生命周期管理,因此您不能像在 Windows 和OSX,不使用 ARC。在 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];
    

    这可移植到所有平台,无需使用IFDEFs 或担心 ARC。

    【讨论】:

    • 你能帮帮我吗,我有类似的问题stackoverflow.com/questions/54927994/… where put {$IFDEF AUTOREFCOUNT}
    • @Pointer 这个问题和这个问题有什么不同?我倾向于将这个问题作为重复来结束
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多