0

I want to make a class registry class that automatically makes a UITableViewCell and when the user presses the button it'll go to that class and run the code.

Currently to do something like that, in the view controller I have to do something like this

Function1Class *function = [[Function1Class alloc] init];
function.view.backgroundColor = [self veryLightGrayColor];
[self.navigationController pushViewController: menu animated: YES];

Then in the data source I make a new case in cellForRowAtIndexPath, and in the delegate I make a case in didSelectRowAtIndexPath for a one line method call.

I'd like to change the code so anyone that wants to add a new class to this page can just do it at one place, something like:

Function1 *function;
[self addClass:function];

And in addClass the "function" passed in will be stored in an array

For the cellForRowAtIndexPath and didSelectRowAtIndexPath cases they can easily call the right methods by storing in an array.

The problem is how do I automate the initialization of each class object passed into addClass?

I could get the user to write code like this to add in their class

Function1 *function = [[Function1 alloc] init];
[self addClass:function];

Then the class object is already initialized, but that means during startup EVERY class object is getting initialized, which is a problem if there is a lot of classes. How can I take out a class object from the array, and then initialize it to use it? The class objects are all different classes, so I can't hardcode arrayOfClassObjects[i] = [[Function1 alloc] init];

Thanks

Prudhvi
  • 2,276
  • 7
  • 34
  • 54

1 Answers1

1

Classes are objects, so you can store the classes in an array:

NSArray *functions = @[ [Function1 class],
                        [Function2 class] ];

Then, when you want to instantiate one, you make it indirectly:

id instance = [[functions[0] alloc] init];

So your addClass: should be something like:

- (void)addClass:(Class)cls {
    [self.classList addObject:cls];
}
Rob Napier
  • 286,113
  • 34
  • 456
  • 610