Duck
Duck

Reputation: 36013

running a method with object from a string

at one point of my code I have references to methods as strings and I have their targets. For example, suppose I have an object called myObject and I have a method there called "doSomething:" like this:

- (void)doSomething:(id)sender {
   // do something baby
}

at one point of my code I store references to both object and method doing this:

NSString *myMethod = @"doSomething:";
id myTarget = myObject;

later, in another point of the code I want to do this

[myObject doSomething:self];

but how do I reconstruct the method call to that object from an reference id to the object and from a NSString that represents the method and how do I pass self to that method?

thanks

Upvotes: 1

Views: 154

Answers (2)

Midhun MP
Midhun MP

Reputation: 107231

As said by @Till, you need to use NSSelectorFromString().

You can use the following code:

SEL selector = NSSelectorFromString(myMethod);
if(selector)
{
   [myObject performSelector:selector withObject:self];
}

Upvotes: 1

Till
Till

Reputation: 27597

For converting a string towards a selector, use NSSelectorFromString. For the other way around, use NSStringFromSelector.

Convert the selector:

SEL selector = NSSelectorFromString(methodSelectorString);

Invoke method:

[myObject performSelector:selector withObject:self afterDelay:0.0];

From the Foundation reference;

NSSelectorFromString

Returns the selector with a given name.

SEL NSSelectorFromString (
   NSString *aSelectorName
);

Parameters

aSelectorName

A string of any length, with any characters, that represents the name of a selector. Return Value The selector named by aSelectorName. If aSelectorName is nil, or cannot be converted to UTF-8 (this should be only due to insufficient memory), returns (SEL)0.

Discussion To make a selector, NSSelectorFromString passes a UTF-8 encoded character representation of aSelectorName to sel_registerName and returns the value returned by that function. Note, therefore, that if the selector does not exist it is registered and the newly-registered selector is returned.

Recall that a colon (“:”) is part of a method name; setHeight is not the same as setHeight:. For more about methods names, see “Objects, Classes, and Messaging” in The Objective-C Programming Language.


NSStringFromSelector

Returns a string representation of a given selector.

NSString *NSStringFromSelector (
   SEL aSelector
);

Upvotes: 3

Related Questions