开发者

encode and decode int variable in Objective-C

开发者 https://www.devze.com 2023-01-12 08:48 出处:网络
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.

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消