2

I need to do a thing like this:

id myFunction = aMethodDeclaredInMyClass;

[self myFunction]

any help is appreciated!

1
  • 3
    See selectors in Objective-C. First results in google give you everything you need. Commented Apr 26, 2011 at 23:02

3 Answers 3

5

If you know the method in advance:

[self performSelector:@selector(myMethod) withObject:nil];

If you don't know the method name in advance:

SEL selector = NSSelectorFromString(someSelectorStringYoureGiven);
[self performSelector:selector withObject:nil];

Both these examples assume your function accepts no arguments, nor requires execution on a different thread, nor requires delayed execution. There are many variants for all combinations of those conditions (and NSInvocation for even more complex cases). Search performSelector in xcode's documentation to see all the variants.

Sign up to request clarification or add additional context in comments.

1 Comment

perfect: SEL myAction = nil; .. some stuff .. myAction = @selector(actionWalk); .. some stuff .. [self performSelector:myAction]; thank you @Jarret Hardie
3

My guess is you want;

[self performSelector:@selector(aMethodDeclaredInMyClass)]

Read the docs on dynamic dispatch;

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocSelectors.html%23//apple_ref/doc/uid/TP30001163-CH23-SW1

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Introduction/Introduction.html%23//apple_ref/doc/uid/TP40008048

Comments

0

Also see objc_msgSend(). You'd set up a SEL selector variable.

6 Comments

You almost never want to be messing around with objc_msgSend directly. It's like swatting flies with a broadsword. There are cases where you want to use it, but they are very special.
Isn't objc_msgSend() more or less the same as -performSelector:withObject:, but with less overhead? (Genuinely curious.)
@Alex Reynolds: To a certain degree. The thing is that objc_msgSend is more flexible and easier to misuse without realizing it, so using it directly is kind of a bad habit to get into. My phrasing might have been a little sharp, but I don't want to see innocent Googlezens shooting themselves in the foot unnecessarily.
Do you have examples of how it might be misused? Now I'm really curious. I had no idea it is considered verboten.
@Alex Reynolds: What about the cases wherein objc_msgSend_stret would be more appropriate? If you start considering these corner cases, you might have defeated the purpose of using Obj-C in the first place. :)
|

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.