Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate Class Programmatically in iOS

I am working a big iOS project, the design is not a nice as I would like it to be, but I must stick to it. (life can be a bitch sometimes).

The thing is that we have a Library that basically let's you browse a catalog. You have a filter, where you specify a certain search criteria, and you are presented with a list were you can press on the items that you are interested. When you press an item, you can see a more detailed description of it.

The company were a work for, sells this same software to many different companies that have different catalogs. The idea is that the Library has all the main functionality, and the project that use it, might in some way extend or completely override some of the given interfaces.

To give you an example, imagine my library has 2 classes that manages 2 views. They would be "FilterViewController" and "DetailsViewControllers". In some place of the code this classes gets instantiated. It would look something like this

Class diagram schema

My approach is something like this:

ProjectA side

// Here I configure the library
Library.FilterViewClass = ProjectAFilterViewController;
Library.DetailsViewClass = ProjectADetailViewController;

ProjectB side

Library.FilterViewClass = ProjectBFilterViewController;
Library.DetailsViewClass = nil;

Library side

// Did the user configure the library?
if(self.FilterViewClass == nil){
    // I alloc the default ViewController
    myFilterViewController = [[FilterViewController alloc] init]; 
}else{
    // Here I would like to alloc the custom ViewController
    myFilterViewController = [[Library.FilterViewClass alloc] init]; // DaProblem!
}

The problem with that approach is that I actually don't know if it's possible to instantiate object programmatically. Or at least I don't know how. Maybe I am using the wrong approach, some direction would be appreciated. Txs in advance!

like image 443
Ignacio Oroná Avatar asked Nov 24 '11 16:11

Ignacio Oroná


2 Answers

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];
like image 64
beryllium Avatar answered Oct 02 '22 14:10

beryllium


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];
like image 36
tarmes Avatar answered Oct 02 '22 12:10

tarmes