如何在init中初始化Objective C类变量?

时间:2016-11-25 01:39:40

标签: ios objective-c constructor

@interface中,我有这个声明:

@interface myClass {
   NSDictionary * myData;
}

@property (nonatomic, assign) NSDictionary * data;
+ (id) initWithData:(NSDictionary *)data;

@end

@implementation中,我有以下代码:

@implementation

@synthesize data;

+ (id) initWithData:(NSDictionary *)freshData {
    self = [super init];
    if (self) {
        self->data = freshData;
    }
    return self;
}

@end

但我在Incomplete definition of type 'struct objc_class上收到错误self->data

如果我将其更改为self.data,则会收到错误Member reference type 'struct objc_class *' is a pointer; did you mean to use '->'?

如果删除self,我会在类方法中获得错误`实例变量'数据'。

但是如果我将方法类型从+(类方法)更改为-(实例方法),我就无法访问init。

我无法通过将作业从data更改为myData来解决此错误。

我应该如何制作构造函数?

我从(但没有帮助)学到的链接是:

3 个答案:

答案 0 :(得分:2)

你也可以这样做

+ (id) initWithData:(NSDictionary *)freshData {
    return [[self alloc]initWithData:freshData];
}
- (instancetype) initWithData:(NSDictionary *)freshData {

    NSParameterAssert(freshData != nil);

    self = [super init];

    if (self) {
        self.data = freshData;
    }

    return self;
}

答案 1 :(得分:2)

一般来说,我不希望init*方法成为类方法。通常,您有一个名为default*shared**withDictionary:的类方法。因此对于名为myClass的类,我希望看到这个:

+ (myClass*)myClassWithDictionary:(NSDictionary*)dict
{
    return [[myClass alloc] initWithDictionary:dict];
}

例如,当静态分析器分析您的代码时,这很重要。命名在Objective-C中很重要,并提示编译器(和分析器)关于代码的意图。

答案 2 :(得分:1)

不要使用公共init方法(+)

+ (id) initWithData:(NSDictionary *)data;

更改为

- (instancetype) initWithData:(NSDictionary *)data;

我强烈建议您使用instancetype代替idreference