当您运行 self=[super init] 并且它返回 nil 时,正确的响应是什么?
我在 may 类的实例中运行此代码:
-(id)init {
self = [super init];
if (self) {
// my init code here
}
return self;
}
...并且 self 返回 nil。我知道这是正确的程序并且应该这样做。但如果 self 返回 nil,我的反应应该是什么?发出程序已失败并正在终止的警报?忽略它?或者是否有推荐的安全继续程序?
I run this code in the instance of may class:
-(id)init {
self = [super init];
if (self) {
// my init code here
}
return self;
}
...and self returns nil. I KNOW this is correct procedure and should be done. But if self were to return nil, what should my response be ? Throw up an alert that the program has failed and is terminating ? Ignore it ? Or is there a recommended procedure to safely continue ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我知道这听起来像是递归的,但我认为在这种情况下最好的做法是返回 nil。
当从初始化器返回 nil 值时,您无法真正预测对象的状态是什么,因此最安全的做法就是处理该对象。从初始化程序来看,这意味着只将 nil 返回给调用者。
当alloc]init]ing时,我总是觉得这种情况会导致泄漏,所以我一直很犹豫是否简单地简单地调用alloc]init]。
I know it sounds recursive, but I think the best thing to do in this instance is to return the nil.
You cannot really predict what the state of the object is when getting a nil value returned from the initializer, so the safest thing to do is just dispose of the object. From the initializer, that means just returning nil to the caller.
When alloc]init]ing, it always seemed to me like this situation would lead to leaks, so I've always been quite hesitant to simply call alloc]init] blindly.
我个人从未见过这种情况发生。但由于 objc 处理 nil 的能力非常好,所以我不会担心除了你已经通过返回从 super 收到的 nil 所做的事情之外还有特殊情况。
I've never seen it happen personally. But since objc handles dealing with nil so well I wouldn't worry about having special cases beyond what you're already doing by returning the nil you received from the super.