在Objective-C中分配给自己 [英] Assigning to self in Objective-C

查看:89
本文介绍了在Objective-C中分配给自己的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自C ++世界,因此分配this的概念让我感到震惊:

I'm from the C++ world so the notion of assigning this makes me shudder:

this = new Object; // Gah!

但是在Objective-C中,有一个类似的关键字self,对此完全可以接受:

But in Objective-C there is a similar keyword, self, for which this is perfectly acceptable:

self = [super init]; // wait, what?

许多示例Objective-C代码在init例程中使用以上代码.我的问题:

A lot of sample Objective-C code uses the above line in init routines. My questions:

1)为什么分配给self有意义(诸如因为语言允许"之类的答案不计算在内)

1) Why does assignment to self make sense (answers like "because the language allows it" don't count)

2)如果我未在init例程中分配self,会发生什么情况?我会将我的实例置于某种危险之中吗?

2) What happens if I don't assign self in my init routine? Am I putting my instance in some kind of jeopardy?

3)当以下if语句失败时,它是什么意思,我应该怎么做才能从中恢复:

3) When the following if statement fails, what does it mean and what should I do to recover from it:

- (id) init
{
    self = [super init];

    if (self)
    {
        self.my_foo = 42;
    }

    return self;
}

推荐答案

这是新手经常挑战的主题:

This is a topic that is frequently challenged by newcomers:

  • Wil Shipley: self = [stupid init];
  • Matt Gallagher: What does it mean when you assign [super init] to self?
  • Apple documentation: Implementing Initializers
  • Cocoa-Dev: self = [super init] debate

基本上,它是基于这样的想法,即超类可能已经重写了指定的初始化程序,以返回与从+alloc返回的对象不同的对象.如果未将super的初始化程序的返回值分配给self,则可能会处理部分初始化的对象(因为super初始化的对象与您所使用的对象不同).重新初始化).

Basically, it stems from the idea that a superclass may have over-ridden the designated initializer to return a different object than the one returned from +alloc. If you didn't assign the return value of super's initializer into self, then you could potentially be dealing with a partially initialized object (because the object that super initialized isn't the same object that you're initializing).

总的来说,super返回不同的内容非常少见,但确实在某些情况下会发生.

On the whole, it's pretty rare for super to return something different, but it does happen in a couple of cases.

这篇关于在Objective-C中分配给自己的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆