initWithCoder works, but init seems to be overwriting my objects properties?

Posted by Zigrivers on Stack Overflow See other posts from Stack Overflow or by Zigrivers
Published on 2010-06-05T17:10:52Z Indexed on 2010/06/05 17:12 UTC
Read the original article Hit count: 304

Filed under:

Hi guys,

I've been trying to teach myself how to use the Archiving/Unarchiving methods of NSCoder, but I'm stumped.

I have a Singleton class that I have defined with 8 NSInteger properties. I am trying to save this object to disk and then load from disk as needed.

I've got the save part down and I have the load part down as well (according to NSLogs), but after my "initWithCoder:" method loads the object's properties appropriately, the "init" method runs and resets my object's properties back to zero.

I'm probably missing something basic here, but would appreciate any help!

My class methods for the Singleton class:

+ (Actor *)shareActorState
{
    static Actor *actorState;

    @synchronized(self) {
        if (!actorState) {
            actorState = [[Actor alloc] init];
        }
    }

    return actorState;  
}


-(id)init
{
    if (self = [super init]) {

        NSLog(@"New Init for Actor started...\nStrength: %d", self.strength);
    }

    return self;
}

-(id)initWithCoder:(NSCoder *)coder
{

    if (self = [super init]) {

        strength = [coder decodeIntegerForKey:@"strength"];
        dexterity = [coder decodeIntegerForKey:@"dexterity"];
        stamina = [coder decodeIntegerForKey:@"stamina"];
        will = [coder decodeIntegerForKey:@"will"];
        intelligence = [coder decodeIntegerForKey:@"intelligence"];
        agility = [coder decodeIntegerForKey:@"agility"];
        aura = [coder decodeIntegerForKey:@"aura"];
        eyesight = [coder decodeIntegerForKey:@"eyesight"];
        NSLog(@"InitWithCoder executed....\nStrength: %d\nDexterity: %d", self.strength, self.dexterity);
        [self retain];

    }

    return self;                 
}

-(void) encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeInteger:strength forKey:@"strength"];
    [encoder encodeInteger:dexterity forKey:@"dexterity"];
    [encoder encodeInteger:stamina forKey:@"stamina"];
    [encoder encodeInteger:will forKey:@"will"];
    [encoder encodeInteger:intelligence forKey:@"intelligence"];
    [encoder encodeInteger:agility forKey:@"agility"];
    [encoder encodeInteger:aura forKey:@"aura"];
    [encoder encodeInteger:eyesight forKey:@"eyesight"];
    NSLog(@"encodeWithCoder executed....");
}


-(void)dealloc
{
    //My dealloc stuff goes here
    [super dealloc];
}

I'm a noob when it comes to this stuff and have been trying to teach myself for the last month, so forgive anything obvious.

Thanks for the help!

© Stack Overflow or respective owner

Related posts about objective-c