gpt4 book ai didi

iphone - 在 Objective-C 中,如何处理 [[myView alloc] init] 返回 nil?

转载 作者:可可西里 更新时间:2023-11-01 04:31:28 26 4
gpt4 key购买 nike

似乎在一本书的代码示例中,总是定义init,以便仔细检查self是否能够存在。

-(id) init {

self = [super init];
if (self) {
// initialize
}
return self;
}

然而,在返回时,没有任何代码检查对象是否能够存在。但是否应该检查,又该如何处理呢?如果对象不存在,是否意味着系统内存严重不足,甚至弹出错误消息也不可能?

最佳答案

However, upon return, none of the code at all checks whether the object is able to exist. But should it be checked, and how can it be handled?

通常,当返回 nil 时,子类会忽略错误处理。当返回 nil 时,错误处理通常留给调用者。如惯用的 -init 所示:

- (id)init {
self = [super init];
if (self) {
// initialize
}
return self;
}

同样,如果基在init中重新分配了self,那么self就会被重新分配(self = [super init]; )。效果很好。

如果你未能将 self 赋值给 super 的初始化器的结果,或者如果你未能检查 nil,那么你可能持有悬空/释放指针 (EXC_BAD_ACCESS),并且您可能无法正确初始化 ivar(如果未遇到 EXC_BAD_ACCESS,您将有效地将它们分配到另一个区域).

两种情况更详细:

self 分配失败

- (id)init {
[super init];
if (self) {
// self was not reassigned. if super returned an object other
// than self, then our ivar would be freed, reused, or sitting
// in an autorelease pool, and the returned instance's ivar
// would not be assigned -- we wouldn't know the address.
ivar = 1;
}
return self;
}

检查 nil 失败

- (id)init {
self = [super init];
// super returned nil. ivar is an invalid region:
ivar = 1;
return self;
}

是的,这两个我都看过。


If the object can't exist, does that mean the system is seriously out of memory, and even popping up an error message will also be impossible?

完全没有。许多初始化程序返回 nil 表示“不能在此上下文中执行”,或者如果存在简单的参数错误。

关于iphone - 在 Objective-C 中,如何处理 [[myView alloc] init] 返回 nil?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10358678/

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