Richard Grossman
Richard Grossman

Reputation: 731

Call a method in a class instantiated with classFromString?

In another question ( how to instantiate an object of class from string in Objective-C? ), this was suggested:

id myclass = [[NSClassFromString(@"MyClass") alloc] init];
[myclass FunctioninClass];

However, [myClass FunctioninClass] yields an error because the compiler has no idea if FunctioninClass exists.

I do know the classes that can be there are all descendants of one parent. And that parent has the prototype of the method I want to call, except I want to call the overridden descendant method. Does that suggest a solution?

Upvotes: 0

Views: 598

Answers (3)

Paul Peelen
Paul Peelen

Reputation: 10329

After @user523234's comment, I decided to improve my answer and correct it. His answer, however, is in my opinion not good enough and will crash your code in case the selector is not available.

So here is the solution:

id myclass = [[NSClassFromString(@"MyClass") alloc] init];

if ([myclass respondsToSelector:@selector(FunctioninClass)])
{
    [myClass performSelector:@selector(FunctioninClass)];
}

Using the - respondsToSelector: will make sure you check wether the sector exists in the class. However, you will need to use the preformSelector everytime. I am unsure if you can dynamically type-cast an identifier.

Upvotes: 2

user523234
user523234

Reputation: 14834

You can use performSelector instead. Here is Apple doc

[myClass performSelector:@selector(FunctioninClass)];

Upvotes: 4

David Gelhar
David Gelhar

Reputation: 27900

Since you know that all the possible classes derive from one parent class, and that class includes the method you need, simply:

ParentClass *myclass = [[NSClassFromString(@"MyClass") alloc] init];
[myclass FunctioninClass];

The fact that you're using NSClassFromString to choose which subclass to instantiate isn't even really relevant. This is just a simple inheritance situation: myclass "is-a" ParentClass, so you can call any method of ParentClass on it.

Upvotes: 1

Related Questions