Frans
Frans

Reputation: 57

Call existing object with NSString and call method - objective-c

another easy one, for you guys I mean:

I need to call a method on an existing object like this:

[object method];

The name of the object however, is different (this code is for a superclass, the children all have different names) each time. So I want to call the object with an NSString like this:

NSString *objectName = @"object";
[objectName method];

I've read about NSClassFromString (I've been looking for hours now), but that doesn't work. Then I get the following error: "no known class method for selector 'method'".

Do you guys know what I'm doing wrong?

Thanks in advance, Frans

Upvotes: 0

Views: 296

Answers (4)

Johannes Lund
Johannes Lund

Reputation: 1917

If I have understood this correctly and you are talking about class methods, the problem is that you cannot "directly" send a message to the class you´re creating. You have to use performSelector.

SEL method = NSSelectorFromString(@"method");
Class class = NSClassFromString(@"SomeClass");
[(id)class performSelector:method];

Upvotes: -1

Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 22006

There isn't reflection in C, all you can do is to put the object in a dictionary or make it be an ivar.

For example:

@property (nonatomic,strong) id objectName1; // with ARC
@property (nonatomic,strong) id objectName2;
...
@property (nonatomic,strong) id objectNameN;

Then:

NSString* key= @"objectName1"; // objectName1 or whatever
id object= [self valueForKey: key];
[object method];

Upvotes: 1

DivineDesert
DivineDesert

Reputation: 6954

There is no such thing that you are searching for, but you can prevent this error by using isKindOfClass and then performing that method.

Upvotes: -1

kennytm
kennytm

Reputation: 523724

The name of a variable is only known at compile-time. There is no way to get a variable automatically from an NSString. You could, however, but an NSDictionary and call the method, e.g.:

NSDictionary* dict = @{@"object": object, @"obj2": obj2};
NSString* objectName;
[dict[objectName] method];

Upvotes: 5

Related Questions