1

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

2
  • 1
    Hint: You want to create a "selector". Commented Feb 25, 2013 at 12:45
  • use NSSelectorFromString, check the documentation Commented Feb 25, 2013 at 12:46

2 Answers 2

3

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
);
Sign up to request clarification or add additional context in comments.

1 Comment

so? after converting the string to a selector how do I call the method on that object passing self as an object?
1

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];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.