[fpc-pascal]Passing Methods as Callback Procedures?

Jon David Sawyer badquanta6384 at comcast.net
Mon Dec 16 21:27:50 CET 2002


On Mon, 2002-12-16 at 13:57, memsom at interalpha.co.uk wrote:
> > Ok,  I've got some code that looks like this:
> > 
> > fCollection.ForEach(@Self.DoEach);
> > 
> > Now when DoEach() is called its Self and the Self above
> > are not the same...
> > 
> > Is this supposed to happen?
> 
> Yes. 'Self' refers to the Instance you currently reside within. So:
> 
> procedure TMyClass.dosomething(..);
> begin
>   //Self is the instance of TMyClass
> end;
> 
> procedure TCollection.ForEach(..);
> begin
>   //Self is the instance of TCollection
> end;
> 
> Therefore, as 'Self' refers to the Instance the code belongs to, Self will 
> differ in every unique class instance.
> 
> What is the parameter for the 'TCollection.ForEach' method? I assume it's a 
> typed method pointer? You should be able to just use the following:
> 
> fCollection.ForEach(DoEach); //assign this within the class that owns 'DoEach'.
> 
> You don't *need* to use Self, unless your class is out of scope, for example 
> accessed within a 'with' statement and clashes with a class method/property for 
> the with'd class. 
> 
> e.g.
> 
>   procedure TForm1.Button1Clicked(sender: TObject);
>   begin
>     Caption := 'wabble'; // the form
> 
>     with sender as TButton do begin
> 
>       Caption := 'wibble'; //the button not the form
> 
>       Self.Caption := 'wobble'; //the form
> 
>     end;
>   end;
>  
> 
> Matt
> 
> 
I belive you missunderstood what I was trying to do:
I had My object which used another object.  That otehr object was
a tCollection.  tCOllection has a method in which you can pass
a procedure to process each individual item in the collection.

I was trying to pass My object's item handler , MyObject.DoEach, as
the callback procedure for ForEach();  ie:
fCOllection.ForEach(@Self.DoEach);

The compiler doesn't complain about this code.  However the correct
instance of the object is not called when DoEach() is called.

My problem is that prior to going into ForEach() self equals something
diffrent than when ForEach() calls DoEach().
> 
> ---------------------------------------------
> This message was sent using Mistral WebMail.
> http://www.mistral.co.uk/
> 
> 
> 
> _______________________________________________
> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
> http://lists.freepascal.org/mailman/listinfo/fpc-pascal






More information about the fpc-pascal mailing list