28

I've a String who's value is the name of the Class[MyClass] which has to be instantiated, and MyClass has a method called

 -(void)FunctionInClass;

i'm using the method called NSClassFromString to instantiate MyClass.I want to know

1) what does NSClassFromString return?? 
2) what is id? 
3) How to call method -(void)FunctioninClass which is in MyClass using the instance.

how should i proceed , i'm doing it in Objective-C for iPhone app?

2 Answers 2

59

1) what does NSClassFromString return??

It returns a Class, which means you can do [[NSClassFromString(@"MyClass") alloc] init]; see Mac Dev Center Docs for more info.

2) what is id?

See http://www.otierney.net/objective-c.html#idtype

3) How to call method -(void)FunctioninClass which is in MyClass using the instance.

id myclass = [[NSClassFromString(@"MyClass") alloc] init];
[myclass FunctioninClass];
Sign up to request clarification or add additional context in comments.

13 Comments

AFAICT, NSClassFromString is a function, not a class. Point 1 would become NSClassFromString( @"MyClass" )
@ point 1) if NSClassFromString is returning a class, then that class has to be instantiated n then we can call FunctioninClass method right? but @ point 3) we are directly using the class named myclass and calling function. I tried with point 3) its giving me an error: MyClass undeclared(first use in function) and myclass undeclare (first use in function)
Try it like this: id myclass = [[NSClassFromString(@"MyClass") alloc] init]; If the calling code does not know what MyClass is, you'll get the error you described. By using id as the variable type, you avoid this.
if you set a breakpoint in FunctioninClass, does the breakpoint get hit?
Here's a simple cocoa app that seems to do what you're looking for. I created a new Xcode project called "Untitled". pastee.org/ps83z
|
0

NSClassFromString() is a function that returns an Objective-C class. That is, in Objective-C a class is an honourable object. An instance of the "Class" class...

And what is an Objective-C class good for?

for instantiating objects (via alloc init ) for introspection and reflection - to query it for the methods and properties instances of that class are exposed to the user for archiving/de-archiving instances of that class, and... to be able to run class methods (methods that do not require any specific instance of that class.

your last lines actually create an instance of the class whose name is the string passed to NSClassFromString.

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.