我想添加一个返回Class的方法,如下所示:
-(Class) validatorClass{return [AddItemValidator class]; }
并像这样使用它:
self.validator = [[self validatorClass] alloc] initWithParentDirectory:self.parentDirectory];我应该如何声明此方法的返回类型-(Class)以允许仅返回从定义的类扩展的类?
我想返回类似-(Class<'NameValidator'>) ,其中AddItemValidator从NameValidator扩展。
我该如何申报?
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?
最满意答案
正如SomeGuy所提到的,在这种情况下你无法实现编译时的安全性。 相反,您可以使用断言在运行时检查它(总比没有好):
-(Class) validatorClass{ Class theClass = [AddItemValidator class]; NSAssert([theClass isSubclassOfClass:[NameValidator class]], @"Has to return subclass of %@", [NameValidator class]); return theClass; }您甚至可以进一步在此处应用Factory模式,以将验证器类与正在验证的类分离:
@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 } }然后创建你的验证器:
self.validator = [[NameValidatorFactory validatorForObject:self] initWithParentDirectory:self.parentDirectory];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];更多推荐
发布评论