Delphi TCollectionItem 的属性中可以有 TFmxObject 吗?

问题描述 投票:0回答:1

我创建了

TOwnedCollection
/
TCollectionItem
对,试图将
TFmxObject
作为其流媒体属性之一。 但是,保存时,
TFmxObject
(FMyObject) 不会在代码中流式传输。

TMyItem = class(TCollectionItem)
private
  FName: string;
  FMyObject: TMyObject;
public
  constructor Create(Collection: TCollection); overload; override;
  destructor Destroy; override;
  procedure SetMyObject(AValue: TMyObject);
published
  property Name: string read FName write FName;
  property MyObject: TMyObject read FMyObject write SetMyObject;
end;

// TMyItems CLASS not shown as it is standard code

TMyObject = class(TFmxObject)
private var
  FObjectName: string;
published
  property ObjectName : string read FObjectName write FObjectName;
end;

///////////////////////////////////////////////////////
implementation

constructor TMyItem.Create(Collection: TCollection);
begin
  inherited Create(Collection);
  // note: TMyObject.Create(self) will not work
  FMyObject := TMyObject.Create(nil); 
  FMyObject.SetSubComponent(True); // Code suggested by Remy
end;

// AMENDED CODE - is this correct?
procedure TMyItem.SetMyObject(AValue: TMyObject);
begin
  FMyObject.Assign(AValue);
end;

destructor TMyItem.Destroy;
begin
  FMyObject.Free;
  inherited Destroy;
end;

在流信息内,尽管设置了 TMyObject.ObjectName,TMyObject 并未流式传输到 MyItems(即,ObjectName = 'Object1' 未流式传输)

MyItems = <
  item
    Name = 'Test1'
  end
  item
    Name = 'Test2'
  end>

示例代码:

var oNewMyItem := [....]MyItems.Add('Test1');
oNewMyItem.MyObject.ObjectName := 'Object1';  // no errors or AV but does not stream

我需要 MyObject 为

TFmxObject
,因为它在其他地方使用,但我需要它在 TMyItem 的属性中“可流式传输”。

感谢您的任何建议。

delphi collections tcollectionitem
1个回答
0
投票

您需要

TMyItem.Create()
致电
FMyObject.SetSubComponent(true)

此外,您的

MyObject
属性设置器正在直接写入
FMyObject
成员。如果有人将
TMyObject
对象分配给您的属性,它将覆盖该成员,泄漏您创建的原始对象,并顺便获取调用者对象的所有权。两者都不是正确的行为。由于
FMyObject
TMyItem
所有,因此您的
MyObject
属性需要一个调用
FMyObject.Assign()
的 setter 方法。

© www.soinside.com 2019 - 2024. All rights reserved.