Reputation: 77631
I've got a function which creates a few different NSOperation subclasses.
They all use the same parameters the only thing that is different is the Class name.
At the moment I've got a function with a repeating block of code running through the function. Is it possible to pass the Class into a function so that the function can create the objects for me?
i.e.
- (void)createOperationSubclass:(Class*)class withParam:(int)parameter
{
class *operation = [[class alloc] init];
operation.parameter = parameter;
[self.queue addOperation:operation];
}
or something like that? i.e. a generic class loader that doesn't care what the class is.
Then I can run...
[self createOperationSubclass:MyOperationSubclass withParam:10];
[self createOperationSubclass:MyOtherOperationSubclass withParam:5];
Upvotes: 3
Views: 86
Reputation: 35626
Try this one:
- (void)createOperationSubclass:(Class)aClass withParam:(int)parameter
{
id operation = [[aClass alloc] init];
[operation setParameter:parameter];
// If your parameter is an NSNumber: [operation setParameter:@(parameter)];
[self.queue addOperation:operation];
}
Then you just call it like:
[self createOperationSubclass:[WhateverClass class] withParam:1];
PS: Note that class
is a reserved keyword so it's changed to aClass
Upvotes: 2
Reputation: 2926
Use APIs like-
NSStringFromClass(Class aClass);
or
NSClassFromString(NSString *aClassName);
Upvotes: 2
Reputation: 3557
Why dont you do a if/else combination and look which class you got with
if ([myObject isKindOfClass:[AnObject class]]) {
// create object
}
Wouldn't that be much easier?
Upvotes: 2