NSClassFromString works for string literals, returns nil for constructed strings

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

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

but if I build a line with something like

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

what instance- nil. Does it work NSClassFromStringonly with literals? Does something happen at compile time to get the job done NSClassFromString?

+3
source share
3 answers

I never had a problem using this call (provided, I only needed this a few times).

You have:

  • , outClassName ( )?
  • , /? / ?
  • NSClassFromString' - just to ensure that init` 0 ( )
0

, , [ ] . NSStringFromClass, , , ?

0

, . : - .

0

Source: https://habr.com/ru/post/1768648/


All Articles