Objective C - 返回子类的实例而不知道它是什么

时间:2013-12-20 06:02:32

标签: ios objective-c inheritance

我有一个类RestModel : NSObject来处理与Rest API的交互,目的是为每个可通过API访问的模型的子类(例如PageModel : RestModelPhotoModel : RestModel

我想要做的是拥有一个通用的forgeFromDictionary静态方法,该方法将返回子类的实例,但每个子类都是相同的,除非涉及一些自定义实例化。理想情况下,forgeFromDictionary方法会出现在RestModel上,但我可以调用PageModel* myPage = [PageModel forgeFromDictionary:previouslyDefinedDictionary];并获取实际的PageModel对象。

这在Objective-c中是否可行?


这是我尝试过的,不确定我是否走在正确的轨道上:

我知道我可以将静态方法的返回类型设置为instancetype,这显然引用了实际调用该方法的类,如下所示:

+ (instancetype) forgeFromDictionary: (NSDictionary*) dictionary

但是在实际方法中的任何地方使用instancetype都会产生致命错误,所以这不起作用:

+ (instancetype) forgeFromDictionary: (NSDictionary*) dictionary {
    instancetype *object = [[instancetype alloc] init]; # red alert!
    # "use of undeclared identifier 'instancetype'
    object.properties = dictionary;
    object.original = dictionary;
    return object;
}

2 个答案:

答案 0 :(得分:3)

在您的方法中,替换:

instancetype *object = [[instancetype alloc] init];

使用:

RestModel *object = [[self alloc] init];

答案 1 :(得分:1)

如果你想返回实例类而不是超类,也许你可以使用这样的东西:

+(id)forgeFromDictionary:(NSMutableDictionary *)dict{
   Class t = [self class];
   id test = [t new];

    // if you have a common property you can set it here by doing
    if([test respondsToSelector:@selector(property)]){
        //set value here
         [test setProperty:val];

    }
    return test;
}

使用它就像:

 // you need to cast the object since creating it with id type
 YourClass *instance = (YourClass *)[YourClass forgeFromDictionary:yourDictionary];

这将返回实例类而不是超类