tags:

views:

101

answers:

2

In Delphi 7, how to get an instance of a persistent object, given the object identifier in string?

function TForm1.GetObject(Identifier: string): TPersistent;
begin
  //what to do here?
end;

Example of use:

//If I have these declared...
public
  MyString: string;
  MyStringList: TStringList;

//the function will be used something like this
MyString:=TStringList(GetObject('MyStringList')).Text;

Thank you in advance and please apologize me for not being able to express my question clearly in English.

+1  A: 

You could create a published property, which could be accessed via runtime type information (RTTI). See p.73 of Delphi in a nutshell and GetObjectProp.

Writeln((GetObjectProp(O,'ObjField') As TNamedObject).ObjectName);
eed3si9n
+2  A: 

This is very common. You need to hold a list of the object instances by name. You've already suggested this with your string list. This can be used to retrieve the instance by name. So: When you create your object you do:

MyObjList := TStringList.Create;

MyObj := TMyObj.Create;
MyObjList.AddObject( 'Thing', MyObj );

MyObj2 := TMyObj.Create;
MyObjList.AddObject( 'Thing2', MyObj2 );

etc.

Now, to retrieve you simply do:

function GetObject( const AName : string ) : TMyObj;
begin
  I := MyObjList.IndexOf( AName );
  If I = -1 then
    Raise Exception.Create( 'Cant find it' );
  Result := MyObjList[I] as TMyObj;
end;

Bri

Brian Frost