![](/img/trans.png)
[英]What is the correct way to unarchive something that was archived using encodeRootObject:?
[英]What is the correct way to unarchive data from NSuserDefaults?
我將一些基於Objective C的對象存儲到NSuserdefaults中。
要從NSuserDefaults檢索數據,我使用initWithCoder方法。
我已經看到了兩種不同的實現:
實施1
- (id)initWithCoder:(NSCoder *)decoder {
self = [super init];
if (self != nil){
//decode properties, other class vars
self.variable = [decoder decodeObjectForKey:@"variable"];
}
return self;
}
實施2
- (id)initWithCoder:(NSCoder *)decoder {
self = [[CustomClass alloc] init];
if (self != nil){
//decode properties, other class vars
self.variable = [decoder decodeObjectForKey:@"variable"];
}
return self;
}
哪種方法正確?
兩者有什么區別?
您不應該在方法中分配對象(分配發生在調用init / initWithCoder之前)。 您的代碼應如下所示:
- (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (self != nil){
//decode properties, other class vars
self.variable = [decoder decodeObjectForKey:@"variable"];
}
return self;
}
這確實不是NSUserDefaults實現的區別,無論您的類是否是子類,都沒有區別。 子類調用[super init]以獲得其超類的屬性(例如2),否則,您可以分配並初始化自定義類(例如1)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.