views:

1139

answers:

2

Why does NSClassFromString return nil ? As per the definition it has to return class name. How should i take care to rectify this problem. since i need to instantiate a class from string and call the method which is in the class using the instance created.

This is how my code looks like.

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

but the method_from_class function is not being called,control is not going into it.and my code is error free.any idea me how to solve this in Objective-C.?

+2  A: 

The Documentation for the function says:

Return Value The class object named by aClassName, or nil if no class by that name is currently loaded. If aClassName is nil, returns nil.

An example of how this should be properly used is as follows:

Class dictionaryClass = NSClassFromString(@"NSMutableDictionary");
id object = [[dictionaryClass alloc] init];
[object setObject:@"Foo" forKey:@"Bar"];
Dave DeLong
But the value in the string @"Class_from_String" has the value of the class name. because i've printed it just above ,before instantiating the class from string.Then how come it is taking as nil?
suse
hey 1've written 3rd line as: ***[object TestMethod];***TestMethod is the method in same class, but stil the control is not going into the method defination.
suse
wat should i do. plz tel me some alternative.
suse
hi Dave.. do u have any idea, for alternative methos for NSClassFromString in Objective-C?My main purpose is to create an instance of class from string and to call a method using the instance created.
suse
@suse: Either your string isn't getting loaded correctly or _there is no class with that name known to the runtime,_ in which case you have to load it first.
Georg
A: 

Why not decomposing all these calls ? This way, you can check the values between the calls:

Class myclass = NSClassFromString(@"Class_from_String");
id obj = [[myclass alloc] init];
[obj method_from_class];

By the way, is method_from_class an instance method or a class method ? If it is the later, then you can directly call method_from_class on the myclass value:

[myclass method_from_class];
Laurent Etiemble