gpt4 book ai didi

objective-c - NSInteger 和 decodeInteger :forKey: Problems

转载 作者:搜寻专家 更新时间:2023-10-30 19:55:56 25 4
gpt4 key购买 nike

我有以下两种归档方式:

    - (void) encodeWithCoder: (NSCoder *) encoder {
[encoder encodeObject:self.exercises forKey:@"exercises"];
[encoder encodeObject:self.title forKey:@"title"];
[encoder encodeObject:self.description forKey:@"description"];
[encoder encodeInteger:self.idnum forKey:@"idnum"];
[encoder encodeInteger:self.rating forKey:@"rating"];
[encoder encodeInteger:self.frequency forKey:@"frequency"];
NSLog(@"Encoding!");

}

- (id) initWithCoder: (NSCoder *) decoder {
self.exercises = [[decoder decodeObjectForKey:@"exercises"] retain];
self.title = [[decoder decodeObjectForKey:@"title"] retain];
self.description = [[decoder decodeObjectForKey:@"description"] retain];
self.idnum = [[decoder decodeIntegerForKey:@"idnum"] retain];
self.rating = [[decoder decodeIntegerForKey:@"rating"] retain];
self.frequency = [[decoder decodeIntegerForKey:@"frequency"] retain];
NSLog(@"Decoding!");
return self;
}

还有一个标题:

    @interface Workout : NSObject{

NSMutableArray *exercises;
NSString *title;
NSString *description;
NSInteger idnum;
NSInteger rating;
NSInteger frequency;
}

- (void) encodeWithCoder: (NSCoder *) encoder;
- (id) initWithCoder: (NSCoder *) decoder;

@property(nonatomic,retain) NSMutableArray *exercises;
@property(nonatomic,retain) NSString *title;
@property(nonatomic,retain) NSString *description;
@property(nonatomic) NSInteger idnum;
@property(nonatomic) NSInteger rating;
@property(nonatomic) NSInteger frequency;
@end

看起来很简单。 encodeInteger 接受一个 NSInteger,我将其传递给它,decodeIntegerForKey 返回一个 NSInteger,但我得到了这个奇怪的错误:

警告:无效的接收者类型“NSInteger”

当执行 decodeIntegerForKey 指令时,我得到一个 exec bad access。

为什么会这样?

最佳答案

发布的代码有几个问题。第一:

self.idnum =       [[decoder decodeIntegerForKey:@"idnum"] retain];

该代码正在将“保留”发送到 NSInteger。 NSIntegers 不是对象,它们只是标量。那是非法的。只需使用它:

self.idnum =       [decoder decodeIntegerForKey:@"idnum"];

接下来,这段代码:

self.exercises =   [[decoder decodeObjectForKey:@"exercises"] retain];

保留过多,会造成泄漏。由于您声明了如下练习:

@property(nonatomic,retain) NSMutableArray *exercises; 

“保留”意味着当您调用 setter 时,它将保留传入的值,然后再将其粘贴到“练习”实例变量中。不过,您在调用 setter 之前保留,所以这是双重保留。

您可以通过将代码更改为以下之一来解决此问题:

exercises =   [[decoder decodeObjectForKey:@"exercises"] retain];

或者:

self.exercises =   [decoder decodeObjectForKey:@"exercises"];

关于objective-c - NSInteger 和 decodeInteger :forKey: Problems,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2018978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com