Chen Li Yong Chen Li Yong - 1 year ago 180
iOS Question

How to initialize Objective C class variable in init?

In the

, I have this declaration:

@interface myClass {
NSDictionary * myData;

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


In the
, I have this code:


@synthesize data;

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


But I got error
Incomplete definition of type 'struct objc_class

If I change it into
, I got error
Member reference type 'struct objc_class *' is a pointer; did you mean to use '->'?

If I remove the
, I got error `Instance variable 'data' accessed in class method.'

But if I change the method type from
(class method) to
(instance method), I cannot access the init.

And I cannot fix this error by change the assignment from

How should I make a constructor?

The link that I have learned from (but not helping) are:

Answer Source

You can do it like this also

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

    NSParameterAssert(freshData != nil);

    self = [super init];

    if (self) { = freshData;

    return self;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download