从 NSuserDefaults 取消归档数据的正确方法是什么?

发布于 2025-01-03 07:19:15 字数 750 浏览 4 评论 0原文

我将一些基于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

卖梦商人 2025-01-10 07:19:15

你不应该在方法中分配你的对象(分配发生在调用 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;
}

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:

- (id)initWithCoder:(NSCoder *)decoder {
    self = [super initWithCoder:decoder];
    if (self != nil){
        //decode properties, other class vars
        self.variable = [decoder decodeObjectForKey:@"variable"];
    }
    return self;
}
迷迭香的记忆 2025-01-10 07:19:15

这实际上不是 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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文