How can I dynamically create an instance of a class?

Example:

I have 10 view controllers that are all allocated and initialized in the same way:

UIViewController *controller = [[MyViewController alloc] initWithNib];

(note that -initWithNib is a custom method of the UIViewController subclass)

The next class of the view controller is OtherViewController, etc. I want to load view controllers lazily only when I need them. But for this I need to have some kind of "array" that will give me the appropriate class for the given index, so that I can initialize it.

I ended up creating a method with a large switch-statement statement that simply makes this unpleasant distribution and initialization separate for each individual view controller. I am not happy with that. It would be much better if I could assign the corresponding class to a variable, and then at the end of the switch statement just select and initialize this class from the variable.

Is there any way to achieve this?

EDIT: I found a function

id class_createInstance(Class cls, size_t extraBytes)

and each class has a "class" property. But I cannot assign it to an instance variable. This does not work:

Class cls = [UIImage class];
cls *image = [cls imageNamed:@"avatar.png"];

The first line is compiled. But the second gives an error: "image is undeclared."

+3
source share
5 answers

, . :

static Class factory[2];

factory[0] = [MyViewController1 class];
factory[1] = [MyViewController2 class];
...

(classid , , :

-(UIViewController*)createViewController:(int)classid
{
    return [[factory[classid] alloc] init];
}

, MyFactory, :

MyFactory * fac = [[MyFactory alloc] init];
UIViewController * v1 = [fac createViewController: 0]; // typed
id v2 = [fac createViewController: 1]; // untyped

, :

#include <objc/objc-runtime.h>

id object = [[NSClassFromString(@"TheClassName") alloc] init];

UIViewControllers, .

+13

:

 id controller = class_createInstance(NSClassFromString(@"your class name"), 0/*extra bytes*/);

Objective-C

+6

: http://igotosoft.blogspot.com/2009/05/dynamically-creating-viewscontrollers.html , , ClassConstructor, , init , . , [myClassConstructor create];

+1

, , Reflection. , objective-c, Google .

0

Objective C . Objective-C 2.0 Runtime,

0

Source: https://habr.com/ru/post/1709127/


All Articles