Re: Calling a method based on a string
Re: Calling a method based on a string
- Subject: Re: Calling a method based on a string
- From: "Louis C. Sacha" <email@hidden>
- Date: Mon, 11 Oct 2004 14:58:49 -0700
Hello...
Also note that this will not work for the particular example you gave
(drawRect:), since you can only pass an object pointer as a
parameter. The performSelector:withObject: method will work fine as
long as the selector you are calling takes an id (or NSArray *,
NSString *, etc) as the argument.
One way to be able to pass structs and other values is to create a
wrapper method for the method you want to call that accepts an
NSValue instance. Making an NSValue to wrap the NSRect is simple,
just use the NSValue valueWithRect: class method. So, (if you
actually wanted to call drawRect: in this manner) a wrapper method
would look like this for example
@implementation NSView (WrappedStructMethods)
- (void)wrapped_drawRect:(NSValue *)wrappedRect
{
NSRect rect = [wrappedRect rectValue];
[self drawRect:rect];
}
@end
Then in whatever method where you are dispatching the message, you
would use the string for the wrapping method, ie @"wrapped_drawRect:"
(as Fritz mentioned, colons are very important), and pass the NSValue
as the object.
[someObject
performSelector:NSSelectorFromString(@"wrapped_drawRect:")
withObject:myRectValue];
Hope that helps,
Louis
[objectB performSelector:NSSelectorFromString(@"drawRect")
withObject:myDrawRect];
I've looked though tons of docs and tried my best to search the
archives for this; but I just can't find a answer....
Is it possible to call a method at runtime when all my app knows is
a string of the method?
For example object A has a string called "drawRect" and a rectangle
called myDrawRect
Then I want object B to perform drawRect with myDrawRect as it's parameter.
So it would be something like [objectB doMethod:@"drawRect"
withParameter:myDrawRect];
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden