gpt4 book ai didi

objective-c - 在 if 条件下 self 赋值 - Objective-C

转载 作者:搜寻专家 更新时间:2023-10-30 19:55:36 25 4
gpt4 key购买 nike

self 是指向当前对象的隐藏实例变量:

- (id) initWithAmount:(double)theAmount forBudget:(Budget *)aBudget{

if(self = [super init]){

budget = aBudget;
amount = theAmount;

}
return self;
}

是否类似于

this.budget=super.aBudget;
this.amount=super.theAmount;

通常:

if(control)//true or false
{
//stmts will get executed
}

但是这里没有返回真值,而是给 self 赋值了 super。为什么会这样?

是不是类似于constructor.如何在 Objective-C 中使用构造函数(默认、参数化和复制)

最佳答案

因为赋值表达式也返回赋值的结果,

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

相当于:

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

并且因为 if 不仅测试纯 bool 值,而且处理非零、非 NULL 或非 nil 的所有内容为真,if 语句测试赋值后 self 是否为 nil

当我们编写自己的 init 方法时,我们应该将 [super init] 分配给 self 因为 init 方法可以自由返回与方法接收者不同的对象。如果我们只是调用 [super init] 而没有将其分配给 self,我们可能会初始化一个与 self 不同的对象,这显然是不可取的。

关于objective-c - 在 if 条件下 self 赋值 - Objective-C ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5764210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com