Sunday, August 8, 2010

Creating class instance from NSString in iPhone SDK

In my post Creating object dynamically from class name in Qt  I tried to create class instance from string in Qt. I thought if same can be done in iPhone SDK or not.

In iPhone SDK we can create class instance from class name using NSClassFromString function.

My sample code to test  NSClassFromString is as below.

My base class for dummy parsing

@interface Parser : NSObject {
}
-(void) parse;
@end

@implementation Parser
-(void) parse
{
NSLog(@"Parser::parse");
}
@end

Two derived class, which actually just print and dose nothing useful

@interface Parser1 : Parser {
}
@end

@implementation Parser1
-(void) parse
{
NSLog(@"Parser1::parse");
}
@end

@interface Parser2 : Parser {
}
@end

@implementation Parser2

-(void) parse
{
NSLog(@"Parser2::parse");
}
@end

and after dummy code, some useful code which does actual work and test code for testing

-(void) parse:(NSString*) aParserName
{
NSLog(@"trying to parse for %@", aParserName);
Parser* parser = [[NSClassFromString(aParserName) alloc] init];
[parser parse];
[parser release];
}

-(void) test
{
[self parse:@"Parser1"];
[self parse:@"Parser2"];
}

and finally output

2010-08-08 23:23:43.050 Test[2330:207] trying to parse for Parser1
2010-08-08 23:23:43.052 Test[2330:207] Parser1::parse
2010-08-08 23:23:43.054 Test[2330:207] trying to parse for Parser2
2010-08-08 23:23:43.055 Test[2330:207] Parser2::parse

No comments:

Post a Comment