emenegro
emenegro

Reputation: 6971

Could [NSMutableArray array] return nil?

For example in low memory conditions. I'm reading third party code and I saw this

NSMutableArray *array = [NSMutableArray array];

if (array != nil) {

    [array addObject:anObject];
}

I've never check this after creating an array that way nor alloc+init but now I'm in doubt.

Upvotes: 3

Views: 719

Answers (3)

justin
justin

Reputation: 104698

Technically, it could return nil.

The probability of such a failure at that point is incredibly unlikely. Your app would probably crash or abort before a nil were returned. Consider it about as unlikely as malloc returning NULL.

My implementations have used checked object creation for years - I cannot remember ever seeing [NSMutableArray array] return nil in that time in development/testing.

Note that this answer is specific to [NSMutableArray array], not any/every initializer/constructor in existence. [NSMutableArray array] is nearly the most 'consistent' class of initializer/constructor in this regard because there is no reason for it to fail under normal circumstances.

Upvotes: 4

Krishnabhadra
Krishnabhadra

Reputation: 34285

There is no need of that nil check. [NSMutableArray array] rarely returns nil. And if it gets to a (memory) situation that this method returns nil, your app is as good as killed.

The only possible case for that method fails is in tight memory constrained situations. iOS will never let memory goes down that much, without doing sufficient actions like memory warnings and purging background apps before.

Also in your example code, even if array is nil, you don't need to check for nil, since method calls on nil are ignored. I am only talking about your example code.

Upvotes: 0

uchuugaka
uchuugaka

Reputation: 12782

Yes. An object instantiation that fails for any reason should return nil unless the method states otherwise.

Upvotes: 4

Related Questions