How to use the method of an object stored in a TList?

My question is pretty simple. I have a TList (called a queue ) containing CNotif class CNotif , and you want to use the is_alive method for these objects.

The problem is that when I use queue.Items[0].is_alive() , I get an Error: Illegal qualifier error message.

I am also confused about how I can create objects in this TList (and as the way the compiler “knows” that stored objects are of this type ...)

What I'm doing now: queue.Add(CNotif.create(timer, title, text, badge)) , but I don't think it should be done that way.

Thank you in advance!

+6
source share
2 answers

The problem is that when I use queue.Items [0] .is_alive (), I get an Error: Illegal qualifier error message.

This is because the compiler has no idea that queue.items[0] is different from a common pointer (see below).

Now I am doing the following: queue.Add (CNotif.create (timer, title, text, icon)), but I don't think it should be done that way.

This is exactly what you need. CNotif.Create creates a new object, and this object is omitted from TObject . It compiles fine because your call to queue.Add expects a pointer, and the Delphi / FreePascal variable containing the instance of the object is actually a pointer. (Both languages ​​obscure the need for dereferencing with MyObj^ for us.)

To use something in queue.Items , you need to tell the compiler that there, besides the general pointer (which, of course, does not have the is_alive method). You do this by typecasting:

 CNotif(queue.Items[0]).is_alive 

Note: there is a shorter way to use TList.Items ; Items declared as the default property for TList , so you can omit it:

 queue[0] 

coincides with

 queue.Items[0] 

and much easier to type.

+10
source

If you are not stuck with the old version of Delphi, you should study the generics.

In the generics.collection block, there is a TList<T> class that you can use here.

 Queue:TList<CNotify>; ... Begin Queue := TList<CNotify>.Create; // remember to clean it up Queue.Add(CNotify.Create(...)); Queue.Add(CNotify.Create(...)); If Queue[0].isAlive then Beep; End; 

I haven't used fpc and lazarus for a while, but in Delphi it is definitely a way to do this. Lists of untyped pointers and throw types all over the place can be a maintenance nightmare.

+6
source

Source: https://habr.com/ru/post/913256/


All Articles