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 decod开发者_Go百科eIntForKey:@"Count"]copy];
return self;
}
[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 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;
}
精彩评论