PDA

View Full Version : best ways of auto assing a id value to an object for a specific class?



noeska
24-08-2009, 12:52 PM
What is the best way of auto assing a id with an value for a object of a specific class?
Use a class var to count the number of instances? Would that limit the number of delphi supported, is fpc capeable of such a thing? Or are the better ways?

Thanks for your answers in advance.

jdarling
24-08-2009, 02:56 PM
Below is the only way I've successfully managed to do this in Lazarus and Delphi. You basically have to go back to the FindComponent method and rely on it giving you an accurate answer. This isn't copy/paste code its from the top of my head so minor tweaks may be necessary (I don't have a compiler handy on this system).

function getValidName(baseName : AnsiString): AnsiString;
var
i : integer;
begin
i := 1;
while assigned(FindComponent(baseName+inttostr(i))) do
inc(i);
result := baseName+inttostr(i);
end;

function getValidNameFromClass(aClass : TPersistentClass) : AnsiString;
begin
result := getValidName(aClass.ClassName);
end;

igel457
25-08-2009, 03:08 PM
If you want an unique id, simply use the object address:


function GetUniqueID(AObj: TObject): AnsiString;
begin
result := AObj.ClassName + IntToStr(Integer(AObj));
end;