Delphi Remove an object from a TObjectList
Asked Answered
A

2

9

I have a TObject list (FileEventObjects := TObjectList.Create(True);) containing one or more objects. The objects need to stay in the list until they are processed. (The object list exists for the duration of the application.)

I'm not entirely sure how to remove a processed object from the list.

Will the object be 'freed' if I do FileEventObjects.Delete(i)

Are there any links to useful examples of TObjectLists in action?

Regards, Pieter.

Airplane answered 1/7, 2011 at 12:9 Comment(1)
If you're ever curious if an object is getting freed, add this line to the destructor: OutputDebugString('Freeing TMyclassName'); You will see it in the event log each time it's called. Or set a breakpoint in TMyclassName.Destroy. You can even turn on Fast MM's memory leak detector, and you'll get warned about objects that didn't get freed properly.Photomultiplier
G
15

If you pass True to the TObjectList constructor (it is also True by default), the list frees any object as soon as you remove it from the collection, no matter if you use Delete, Remove or Clear.

Apart from this, TObjectList can be used just like TList.

Girdle answered 1/7, 2011 at 12:15 Comment(3)
I was afraid of answering this one, as I didnt know if it freed it when you use those funcs. Thanks for clearing that up, +1 :)Randallrandan
You can use .Extract() to remove an object from the list without freeing it.Obola
Thank you for the prompt answer.Airplane
D
5

always remember to loop backwards like

for i := Pred(objectlist.Count) downto 0 do
begin
  objectlist.items[i].process;
  objectlist.delete(i);
end;

if you loop from 0 to count -1 whilst removing items you will get access violations

Diphenylhydantoin answered 1/7, 2011 at 22:49 Comment(1)
Yes, I found that out the hard way yesterday!!Airplane

© 2022 - 2024 — McMap. All rights reserved.