本文介绍了在 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:

基本上,它源于这样一种想法,即超类可能已经覆盖了指定的初始化程序以返回与从 +alloc 返回的对象不同的对象.如果您没有将 super 的初始化程序的返回值分配给 self,那么您可能正在处理一个部分初始化的对象(因为 super initialized 与您正在初始化的对象不同).

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 中分配给自己的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 05:27