Iphone 类错误的Encode-Decode-int属性
这是我的实现Iphone 类错误的Encode-Decode-int属性,iphone,ios,decode,encode,Iphone,Ios,Decode,Encode,这是我的实现 @interface Esame : NSObject{ NSString *nome; int voto; int crediti; int anno; } @property (nonatomic, retain) NSString *nome; - (id)initWithNome:(NSString*)nome voto:(int)voto crediti:(int)crediti anno:(int)anno; @end 我收到同
@interface Esame : NSObject{
NSString *nome;
int voto;
int crediti;
int anno;
}
@property (nonatomic, retain) NSString *nome;
- (id)initWithNome:(NSString*)nome voto:(int)voto crediti:(int)crediti anno:(int)anno;
@end
我收到同样奇怪的错误。。。特别是在NSString中。。。怎么了?尝试在
encodeInt:
之前删除您的条件句;您可能应该始终对所有成员进行编码。此外,您可能应该声明您符合使用@interface Esame:NSObject
进行NSCoding的要求
如果这不起作用,请尝试发布您看到的错误消息。我尝试了,但出现了一些错误。。。我可以存储数组。。。但是当我尝试读取它时,我可以看到新数组有1个元素(正确),但是当我尝试访问它时,我得到了这个错误。***-[CFString isEqualToString:]:发送到已解除分配实例0x796C450的消息,该问题是由此行代码引起的:
nome=[decoder decodeObjectForKey:@“nome”]代码>。您没有保留解码返回的字符串。您应该使用self.nome=…
来保留此字符串,或者手动调用retain
。它可以工作!非常感谢。但我不明白为什么!你能解释一下在这种情况下self的用法吗?谢谢你的问题。。。在另一个类中,我声明了一个Esame类型的项,但我不能使用例如e1.voto或e1.crediti。。。因为它们是int属性。。。如何解决此问题?thanksIt之所以有效,是因为如果您持有对对象的引用,则需要对其调用retain
。使用属性设置器(self.nome=…
,与[self-setNome:…]
相同)为您保留对象(因为您已在@property
声明中指定要保留的属性)。如果为其他成员指定属性,则可以类似地访问它们。
#import "Esame.h"
@implementation Esame
@synthesize nome;
- (id)initWithNome:(NSString*)name voto:(int)voto crediti:(int)crediti anno:(int)anno {
if ((self = [super init])) {
self.nome = name;
}
return self;
}
- (id)initWithCoder:(NSCoder *)decoder {
if (self = [super init]) {
nome = [decoder decodeObjectForKey:@"nome"] ;
voto = [decoder decodeIntForKey:@"voto"];
crediti = [decoder decodeIntForKey:@"crediti"];
anno = [decoder decodeIntForKey:@"anno"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
if (nome) [encoder encodeObject:nome forKey:@"nome"];
if (voto) [encoder encodeInt:voto forKey:@"voto"];
if (crediti) [encoder encodeInt:crediti forKey:@"crediti"];
if (anno) [encoder encodeInt:anno forKey:@"anno"];
}
@end