如何声明返回基类的方法(how to declare method which returns base Class)

编程入门 行业动态 更新时间:2024-10-25 17:18:48
如何声明返回基类的方法(how to declare method which returns base Class)

我想添加一个返回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];

更多推荐

本文发布于:2023-07-20 02:55:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1192076.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:声明   方法   declare   method   base

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!