开发者

WHEN you run self=[super init] and it returns nil, what is the correct response?

开发者 https://www.devze.com 2023-03-31 14:59 出处:网络
I run this code in the instance of may class: -(id)init { self = [super init]; if (self) { // my init code here

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 开发者_StackOverflow社区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 ?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号