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;
}
1
  • 1
    Are you aware that you are not assigning the decoded int to any variable? Commented Aug 17, 2010 at 8:53

2 Answers 2

8

[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.

Sign up to request clarification or add additional context in comments.

Comments

6

V1ru8 is right. However, I prefer to encode ints as NSNumbers. 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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.