views:

37

answers:

2

How do I decode and encode int variables in Objective-C?

This is what I have done so far, but application is terminating at that point.

Whats the mistake here?

-(void)encodeWithCoder:(NSCoder*)coder
{
   [coder encodeInt:count forKey:@"Count"];
}

-(id)initWithCoder:(NSCoder*)decoder
{
   [[decoder decodeIntForKey:@"Count"]copy];
   return self;
}
+5  A: 

[decoder decodeIntForKey:@"Count"] returns an int. And your sending the message copy to that int -> crash.

In Objective-C simple data types aren't objects. So you can't send messages to them. Ints are simple c data types.

V1ru8
+3  A: 

V1ru8 is right, however, I prefer to encode NSNumber's with ints. Like this:

- (void)encodeWithCoder:(NSCoder *)coder {
    [coder encodeObject:[NSNumber numberWithInt:self.count] forKey:@"Count"];
}

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        self.count = [[decoder decodeObjectForKey:@"Count"] intValue];
    }
    return self;
}
Tim van Elsloo
Good point! I would prefere that too.
V1ru8