0

I would like to instantiate a class object by using its unique class name. First I create a NSString object like this

for (i = 1; i <= count; i++)
    NSString *abc = [NSString stringWithFormat:@"item%i",i];

How can I create a class object by using the above NSString object:

myClass *abc;
IsakBosman
  • 1,453
  • 12
  • 19
user2966615
  • 373
  • 4
  • 16
  • id object = [[NSClassFromString(@"NameofClass") alloc] init]; – Jageen Jan 22 '15 at 10:11
  • You could add your objects in an NSDictionary with keys the strings you create in the loop. – Aris Jan 22 '15 at 10:21
  • can you tell me how am i going to do that?? actually i am new – user2966615 Jan 22 '15 at 10:23
  • @user2966615 as you are new there may be a chance that you are attending wrong approach please clear the problem first, Why you want this ? – Jageen Jan 22 '15 at 10:25
  • If I did understand your question correctly, then the answer is Yes! You can create a class that is a subclass of NSString. The interface would be something like: `@interface yourClass : NSString`. – joker Jan 22 '15 at 10:34
  • possible duplicate of [Create objective-c class instance by name?](http://stackoverflow.com/questions/1174093/create-objective-c-class-instance-by-name) – Michał Ciuba Jan 22 '15 at 10:59

1 Answers1

0

To get class from string:

Class cl = NSClassFromString(@"YourClass");

To get class from existing variable:

Class cl = [obj class];

To create an object:

YourClass *myClass = (YourClass *)[cl new];
KlimczakM
  • 12,576
  • 11
  • 64
  • 83