Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Objective-C, how to deal with [[myView alloc] init] returning nil?

It seems that in code example of a book, the init is always defined so that it is careful to check whether self is able to exist.

-(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? 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?

like image 218
nonopolarity Avatar asked Apr 27 '12 22:04

nonopolarity


1 Answers

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?

Typically, error handling is ignored by the subclasses when nil is returned. Error handling is generally left to the caller when nil is returned. As demonstrated in the idiomatic -init:

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

As well, if the base reallocates self in init, then self is reassigned (self = [super init];). works great.

If you fail to assign self to the result of super's initializer or if you fail to check for nil, then you may be holding on to a dangling/deallocated pointer (EXC_BAD_ACCESS), and you may not initialize your ivars properly (you would effectively assign them to another region if an EXC_BAD_ACCESS were not encountered).

The two cases in more detail:

Fail to assign 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;
}

Fail to check for nil

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

and yes, I have seen both of these.


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?

Not at all. Many initializers return nil to say "cannot do in this context", or if there is a simple parameter error.

like image 61
justin Avatar answered Sep 17 '22 09:09

justin