2

How do I formulate

[NSClassFromString(classname) myMethod:param1 more:param2];

such that the compiler does not give a warning saying that +myMethod may not be implemented ?

4 Answers 4

8
[NSClassFromString(classname) performSelector: @selector(myMethod:more:) withObject:param1 withObject:param2];
Sign up to request clarification or add additional context in comments.

Comments

6

Quick & dirty: cast the return of NSClassFromString to id, if myMethod:more: is unique. The method binding doesn't happen until runtime, so the correct impl will be called.

Slightly cleaner: use NSObject's -(id)performSelector:(SEL)aSelector withObject:(id)anObject withObject:(id)anotherObject, if param1 and param2 are ids. It works for class methods too when called on a class object.

Comments

3

Well, since you have multiple arguments, you can’t use -performSelector:withObject:. You’ll have to use what Objective-C uses under the hood, objc_msgSend(). But first you’ll have to cast it. Here’s how:

In your implementation file (.m), add the line #import <objc/message.h> to the top. Then, you need to cast objc_msgSend() appropriately. In this example, we’ll assume that param1 and param2 are Objective-C objects and that -myMethod:more: returns void.

void (*myMsgSend)(id self, SEL _cmd, id param1, id param2);
myMsgSend = (void(*)(id, SEL, id, id))objc_msgSend;

Once you’ve cast it appropriately, call your new function:

myMsgSend(obj, @selector(myMethod:more:), param1, param2);

1 Comment

Do I understand it correctly, first line declares variable myMsgSend which is pointer to a function with (id self, SEL _cmd, id param1, id param2) arguments ?
-1

Try typecasting the value returned by NSClassFromString() to id first.

2 Comments

The type returned from NSClassFromString() is generic and messageable.
NSClassFromString() return value is of type Class, the compiler will warn about calling anything not defined in Class. id is generic, and will make the compiler happy.

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.