在Objective-C中编码和解码int变量

sus*_*use 2 cocoa objective-c

如何在Objective-C中解码和编码int变量?

这是我到目前为止所做的,但应用程序正在终止.

这里的错误是什么?

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

-(id)initWithCoder:(NSCoder*)decoder
{
   [[decoder decodeIntForKey:@"Count"]copy];
   return self;
}
Run Code Online (Sandbox Code Playgroud)

V1r*_*ru8 8

[decoder decodeIntForKey:@"Count"]返回一个int.而你将消息发送copyint- >崩溃.

在Objective-C中,简单数据类型不是对象.所以你不能向他们发送消息.Ints是简单的c数据类型.


els*_*ooo 6

V1ru8是对的.但是,我更喜欢将int编码为NSNumbers.像这样:

- (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;
}
Run Code Online (Sandbox Code Playgroud)