imas145
imas145

Reputation: 1979

Custom NSObject iniWithCoder not called

I have a custom object, LevelContent, which contains some properties. LevelContentconforms to NSCoding, and I have implemented encodeWithCoder: and initWithCoder: methods. I save and fetch the data to Parse.com. Saving works fine like this:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.currentLevelContent];

When I fetch the data, I get the NSDatacorrectly, but when I try to initialize the LevelContentwith the downloaded data, initWithCoder: never gets called. I try to load the LevelContent with this:

LevelContent *content = [NSKeyedUnarchiver unarchiveObjectWithData:data];

Here is the code for encoding/decoding

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.tiles forKey:@"tiles"];
    [aCoder encodeObject:self.attributes forKey:@"attributes"];
    [aCoder encodeObject:self.level forKey:@"level"];
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self == [super init]) {
        self.tiles = [NSMutableArray array];
        [self.tiles addObjectsFromArray:[aDecoder decodeObjectForKey:@"tiles"]];
        self.attributes = [NSMutableDictionary dictionary];
        [self.attributes addEntriesFromDictionary:[aDecoder decodeObjectForKey:@"attributes"]];
        self.level = [Level levelWithTopIndex:0 detailIndex:0];
        self.level = [aDecoder decodeObjectForKey:@"level"];
    }
    return self;
}

Upvotes: 0

Views: 278

Answers (1)

Akhilrajtr
Akhilrajtr

Reputation: 5182

Change if (self == [super init]) to if (self = [super init]) in initWithCoder:

Try this,

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super init]) {
        .....
    }
    return self;
}

Upvotes: 1

Related Questions