MarekM
MarekM

Reputation: 568

how to declare method which returns base Class

I would like to add a method which returns Class like below:

-(Class) validatorClass{

return [AddItemValidator class]; }

and use it like this:

self.validator = [[self validatorClass] alloc] initWithParentDirectory:self.parentDirectory];

How should I declare the return type -(Class) of this method to allow returning only classes which extend from defined class?

I would like to return something like -(Class<'NameValidator'>) where AddItemValidator extends from NameValidator.

How should I declare it?

Upvotes: 0

Views: 74

Answers (1)

Michał Ciuba
Michał Ciuba

Reputation: 7944

As SomeGuy mentioned, you can't achieve compile-time safety in this case. Instead, you can use an assertion to have it checked at the runtime (better than nothing):

-(Class) validatorClass{
    Class theClass = [AddItemValidator class];
    NSAssert([theClass isSubclassOfClass:[NameValidator class]], @"Has to return subclass of %@", [NameValidator class]);
    return theClass;
}

You can even go further and apply Factory pattern here to decouple validator class from the class being validated:

@implementation NameValidatorFactory

+(NameValidator*)validatorForObject:(YourObjectType*)validatedObject {
  //choose proper validator depending on your object's type or anything you want
  if([validatedObject isKindOfClass:[YourObjectTypeSuperclass class]]) {
    return [AddItemValidator alloc];
  }
  else {
  // handle other cases 
  }

  }

And then create your validator like that:

self.validator = [[NameValidatorFactory validatorForObject:self] initWithParentDirectory:self.parentDirectory];

Upvotes: 1

Related Questions