本文介绍了self = [super init]重访的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了这篇文章

I stumbled upon this post In Objective-C why should I check if self = [super init] is not nil?

我能理解:

- (id)initWithString:(NSString *)aString
{
    self = [super init];
    if (self)
    {
        instanceString = [aString retain];
    }
    return self;
}

或:

- (id)init;
{
 if (!(self = [super init]))
   return nil;

 // other stuff
 return self;
}

但我仍然不理解标准模板语法

but I still don't understand the "standard" template syntax

- init {
    if((self = [super init])) {
        // set up instance variables and whatever else here
    }
    return self;
}

有人可以尽可能清楚地说出(3)或多或少的比较(1)或(2)?所有我读到的都是如此令人困惑(为什么人们不能同意纯粹技术性的东西似乎是政治:) :)

Can someone tell as clearly as possible what (3) does more or less compared to (1) or (2) ? All I read is so confusing (why people can't agree with something which is purely technical seems like politics :))

尽管如此,当我读到作者的文章时,和我一样可以模糊地理解它不仅仅是语法糖争论或品味问题。例如据说

Nevertheless as I read authors article, and as I can fuzzily understand it goes far beyond just syntactic sugar debate or matter of taste. For example it is said:

所以如果可能的话,我希望得到Objective C Gurus的深刻哲学答案。

So I'd like to have a deep philosophical answer from Objective C Gurus if possible.

推荐答案

理解(3)的关键是if行

The key to understanding (3) is the if line

if((self = [super init])) {

在C中,每个运算符都有一个返回值,您不必使用它。就像 3 + 4 返回7一样,运算符 = 返回刚分配的相同值。这允许你用它来做这样有趣的事情:

In C, every operator has a return value, you just don't have to use it. So just as 3 + 4 returns 7, the operator = returns the same value that was just assigned. That allows you to do interesting things like this with it:

int a, b, c, d;

a = b = c = d = 5;

(这是因为运营商具有从右到左的关联性。这意味着 a = b = 3; 相当于 a =(b = 3); 所以 b 首先设置为3,然后 a 设置为相同的值。)

(This works because the operator has right-to-left associativity. This means that a = b = 3;is equivalent to a = (b = 3); so b is set to three first, then a is set to that same value.)

所以现在我们可以观察到测试

So now we can observe that the test

if((self = [super init])) {

self = [super init];
if (self) {

他们都做了完全相同的事情。至于首选方案,很多人认为将表达式放入if语句是不好的做法,因为如果你不习惯它,很难注意到。 Apple似乎已经确定了你在模板中列出的第一个例子,并且还为第一个添加了编译器警告,如果你试图在没有愚蠢的双括号 if(())

They all do exactly the same thing, though. As for the preferred option, a lot of people think that putting expressions into if statements is bad practice, as it's hard to notice if you're not used to it. Apple do seem to have settled with the first example you listed in their templates, and have also added a compiler warning for the first, if you try to do it without the stupid double brackets if(()).

这篇关于self = [super init]重访的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 09:11