tags:

views:

68

answers:

2

I am trying to create an instance of a type based on another type passed into a method. I find that NSClassFromString works just fine if used with a string literal, as in

id instance = [[NSClassFromString(@"TheNameOfTheClassIWant") alloc] init];

but if I construct the string with something like

NSString *inClassName = [[protoInstance class] description];
NSString *outClassName = [inClassName stringByAppendingFormat:@"IWant"];
id instance = [[NSClassFromString(outClassName) alloc] init];

that instance is nil. Does NSClassFromString only work with literals? Is something happening at compile time to make NSClassFromString work?

A: 

i've never had a problem using this call (granted, i have only needed it a few times).

you've:

  • verified that outClassName is letter perfect (case-sensitive)?
  • verified that the bundle/class has loaded? you are able to alloc/init a class using the standard approach?
  • verified the output of NSClassFromString' - just to ensure thatinit` isn't returning 0 (as one example)
Justin
More information. If I create an instance of the class in the normal way, then subsequent calls to NSClassFromString work. Otherwise, NSClassFromString itself is returning nil. Do I really have to create an instance of each class in my project before being able to use NSClassFromString?
Jim Flanagan
It must be enough to call the initializer. Do something like [myClassName class] to "register" the class without building an instance
Gobra
@Jim it's possible. you can set a breakpoint `+[SOMEClass load` or `+[SOMEClass initialize]` to test whether the class has loaded into the runtime by the time you call `NSClassFromString`. see also `objc_getClass` and `objc_allocateClassPair` (the latter if you're creating classes at runtime)
Justin
@Gobra That works! Thank you. I'll just hide that messy bit of business in a method that gets called at start up.
Jim Flanagan
As long as it is spelled correctly, `NSClassFromString()` will always work, regardless of whether the class has ever been referenced before. Given that the class is already in the runtime and can be directly instantiated, the name must be mispelled.
bbum
A: 

The only thing I can think of is [Class description] is dubious. Use NSStringFromClass to be sure you got what you want?

Jasconius
description seemed to have been working, but NSStringFromClass is a better technique, thanks.
Jim Flanagan