Instantiate Class Programmatically in iOS Instantiate Class Programmatically in iOS xcode xcode

Instantiate Class Programmatically in iOS


To get class from string you can use this function

Class cl = NSClassFromString(@"MyClass");

To get class of existing variable just call class method.

Class cl = [obj class]; // assuming obj1 is MyClass

Now you can create instance of MyClass

MyClass *myClass = (MyClass*)[[cl alloc] init];...[myClass release];


Use

myFilterViewController = [[[Library.FilterViewClass class] alloc] init]; 

You can also instantiate from a class name, should that be useful to you:

id obj = [[NSClassFromString(@"MyClass") alloc] init];


Class someClass = [Foo1 class];Foo * someObject = [[someClass alloc] init];[someObject bar];Class someClass2 = [Foo2 class];Foo * someObject2 = [[someClass2 alloc] init];[someObject2 bar];

Interface+Implementation:

@interface Foo : NSObject - (void)bar;@end@interface Foo1 : Foo@end@interface Foo2 : Foo@end@implementation Foo- (void)bar {    NSLog(@"abstract foo");}@end@implementation Foo1- (void)bar {    NSLog(@"foo1bar");}@end@implementation Foo2- (void)bar {    NSLog(@"foo2bar");}@end

Output:

2011-11-24 11:24:31.117 temp[21378:fb03] foo1bar2011-11-24 11:24:31.118 temp[21378:fb03] foo2bar