Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 968
emenegro Avatar asked Dec 01 '25 00:12

emenegro


2 Answers

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.

like image 109
justin Avatar answered Dec 02 '25 13:12

justin


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

like image 42
uchuugaka Avatar answered Dec 02 '25 14:12

uchuugaka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!