I have an object class that I create in my program.
The problem is when I create the object I would like to be able to access that object later... There is probably something simple I'm missing here... What is the best way to keep track of objects that are created...? Maybe add them to a TList and access them as I need to?
For example...
If I create my object..
MyStorm := TStorm.Create;
....adjust all properties etc...
Then later create a new instance...
MyStorm := TStorm.Create;
How do I access the first MyStorm?
If I add the objects to a TList would I be able to access them later as needed (maybe by index or something).
The TStorm object represents an object placed on a map. I want to be able to click on the object placed on the map and have the correct object.
I hope this make sense :)
Thanks for any suggestions.
Bryan
Generally speaking you need to do Map.Add(MyStorm). Map can be a TList,
TObjectList, or other container, or a class that holds some kind of list
(can even be a dynamic array, although TList is more simple and
optimized when adding many items). Another idea is to let the container
create the items, just like the TCollection / TCollectionItem concept.
Jens
> The TStorm object
> represents an object placed on a map. I want to be able to click
> on the object placed on the map and have the correct object.
I would suggest a TObjectList. If TStorm has method which
calculates the distance from a given point, then it would be a
simple matter for a given clickpoint to do something like
(untested):
var
FList : TObjectList;
procedure Initialise;
begin
FList := TObjectList.Create;
{ This means the storms will get freed when the list does }
FList.OwnsObjects := true;
end;
procedure TidyUp;
begin
FList.Free;
end;
procedure AddNewStorm(X,Y);
var
newStorm : TStorm;
begin
newStorm := TStorm.Create;
newStorm.SetPosition(X,Y);
FList.Add(newStorm);
end;
function FindObjectByClick(X, Y : integer) : TStorm;
var
index : integer;
aStorm : TStorm;
thisDistance : double;
bestDistance : double;
bestIndex : integer;
const
minClickDistance = ??;
begin
bestIndex := -1;
bestDistance := 1E99; {Some big number}
for index := 0 to FList.Count - 1 do
begin
aStorm := FList[index];
thisDistance := aStorm.GetDistanceFromPoint(X,Y);
if (thisDistance < MinClickDistance) and (thisDistance <
BestDistance) then
begin
bestIndex := index;
bestDistance := thisDistance;
end;
end;
if bestIndex < 0 then
result := nil
else
result := FList[bestIndex];
end;
Thanks to both of you for your suggestions.
I will test TObjectList and TList.
Thanks again,
Bryan