Le 11 févr. 2011 à 13:21, Joanna Carter a écrit :
> Hi folks
>
> I want to store a "method pointer" in a dictionary, recover it and call it
> from elsewhere in code.
>
> So, I have code like this to store the "method pointer":
>
> {
> IMP anIMP = [anObject methodForSelector:@selector( myMethod: )];
>
> [myDictionary setObject:anIMP forKey:myKey];
> }
>
> … and then, elsewhere, I want to recover the IMP from the dictionary and
> invoke the selector on the "self" object that is held in the IMP.
>
> Or have I misunderstood what IMPs do?
>
IMP is just a function pointer. It does not record anything about the class
that declare the corresponding method.
> In C#, a delegate knows about the "this", upon which the method will be
> called, within itself and can simply be called without having to go through
> any gymnastics to get the target object. Isn't this what IMPs do?
>
On Mac OS 10.6, you can use block to get something roughly equivalent to C#
delegate.
To define a delegate, you can do something like this:
typedef void (^mydelegate)(id arg);
To store your delegate in a dictionary, you can do something like this;
[dict setObject:^(id arg) { [anObject myMethod:arg]; } forKey:@"bar"];
And to execute the delegate:
mydelegate delegate = (mydelegate)[dict objectForKey:@"bar"];
delegate(@"Hello World");
-- Jean-Daniel
_______________________________________________
Cocoa-dev mailing list ([email protected])
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com
This email sent to [email protected]