Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a class name as an argument to an object factory in cocoa?

I am working on an object factory to keep track of a small collection of objects. The objects can be of different types, but they will all respond to createInstance and reset. The objects can not be derived from a common base class because some of them will have to derive from built-in cocoa classes like NSView and NSWindowController.

I would like to be able to create instances of any suitable object by simply passing the desired classname to my factory as follows:

myClass * variable = [factory makeObjectOfClass:myClass];

The makeObjectOfClass: method would look something like this:

- (id)makeObjectOfClass:(CLASSNAME)className
{
    assert([className instancesRespondToSelector:@selector(reset)]);
    id newInstance = [className createInstance];
    [managedObjects addObject:newInstance];
    return newInstance;
}

Is there a way to pass a class name to a method, as I have done with the (CLASSNAME)className argument to makeObjectOfClass: above?

For the sake of completeness, here is why I want to manage all of the objects. I want to be able to reset the complete set of objects in one shot, by calling [factory reset];.

- (void)reset
{
    [managedObjects makeObjectsPerformSelector:@selector(reset)];
}
like image 357
e.James Avatar asked Nov 24 '08 21:11

e.James


2 Answers

You can convert a string to a class using the function: NSClassFromString

Class classFromString = NSClassFromString(@"MyClass");

In your case though, you'd be better off using the Class objects directly.

MyClass * variable = [factory makeObjectOfClass:[MyClass class]];

- (id)makeObjectOfClass:(Class)aClass
{
    assert([aClass instancesRespondToSelector:@selector(reset)]);
    id newInstance = [aClass createInstance];
    [managedObjects addObject:newInstance];
    return newInstance;
}
like image 200
Matt Gallagher Avatar answered Oct 19 '22 17:10

Matt Gallagher


I have right a better tutorial on that , please checkout https://appengineer.in/2014/03/13/send-class-name-as-a-argument-in-ios/

like image 43
Mahendra Y Avatar answered Oct 19 '22 16:10

Mahendra Y