从 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;
}
哪个是正确的方法?
这两者有什么区别?
I am storing some Objective C based objects in to NSuserdefaults.
To retrieve data from NSuserDefaults, I use initWithCoder method.
I have seen two different implementations of this:
Implementation 1
- (id)initWithCoder:(NSCoder *)decoder {
self = [super init];
if (self != nil){
//decode properties, other class vars
self.variable = [decoder decodeObjectForKey:@"variable"];
}
return self;
}
Implementation 2
- (id)initWithCoder:(NSCoder *)decoder {
self = [[CustomClass alloc] init];
if (self != nil){
//decode properties, other class vars
self.variable = [decoder decodeObjectForKey:@"variable"];
}
return self;
}
Which is the correct way?
What is the difference between these two?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不应该在方法中分配你的对象(分配发生在调用 init/initWithCoder 之前)。你的代码应该是这样的:
you shouldn't be alloc'ing your object in an method (the alloc takes place before init/initWithCoder is called). your code should look like:
这实际上不是 NSUserDefaults 实现的区别,而是您的类是否是子类的区别。子类调用 [super init] 来获取其超类的属性(例如 2),否则您可以只分配并初始化自定义类(例如 1)。
This really isn't a difference in NSUserDefaults implementation, the difference whether or not your class is a subclass. Subclasses call [super init] to gain the properties of their superclasses (ex. 2), otherwise you can just alloc and init the custom class (ex. 1).