Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you define a Class (objc_class) parameter to have a required subclass at compile time?

Tags:

objective-c

I have the following method:

- (FDModel *)_modelForClass: (Class)modelClass 
    withIdentifier: (NSString *)identifier

which should take in a Class and a identifier, create an instance of modelClass, assign the identifier and do some other work based on the fact that it assumed modelClass is a subclass of FDModel.

I can put in a check that raises some error or exception if [modelClass isSubclassOfClass: [FDModel class]] == NO but I was trying to see if there was a way to enforce this at compile time.

EDIT: I understand that some people see this as a obvious factory method but the modelClass parameter is actually passed in by the user of my library through a delegate callback - (Class<FDModel>)modelClassForDictionary: (NSDictionary *)dictionary;. This question was more aimed at making the user of my library return a Class that has a specific subclass.

like image 690
Reid Main Avatar asked Oct 01 '22 13:10

Reid Main


1 Answers

I would consider the plain answer to your question being no; there is no way of checking if a class passed as a parameter is of a certain kind.

But I'd like to argue that the essence of your question primarily points to a design issue, i.e. can't your instance-generating method be expressed as a factory method? Like so:

@interface FDModel

+ (instancetype)modelWithIdentifier:(NSString *)identifier;

@end

In the above case you would simply do:

[FDModel modelWithIdentifier:anIdentifier];

The actual class returned (and the initialisation logic) being specified by the factory method implementation through subclassing of the FDModel class:

@implementation FDModelSubclass

+ (instancetype)modelWithIdentifier:(NSString *)identifier
{
    FDModel *model = [super modelWithIdentifier:identifier];
    if (model)
    {
        // do additional init stuff
    }
    return model;
}

@end

Nothing to check, no chance to go wrong.

like image 144
insys Avatar answered Nov 13 '22 18:11

insys