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 li开发者_StackOverflow中文版terals? Is something happening at compile time to make NSClassFromString
work?
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 that
init` isn't returning 0 (as one example)
The only thing I can think of is [Class description] is dubious. Use NSStringFromClass to be sure you got what you want?
Check that the class is included in Build Phase of your target. I had the same issue - the class had been dropped out of the build phase due to an unrelated change.
精彩评论