Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I always check if [[NSArray alloc] init…] returns nil?

Should I always check if [[NSArray alloc] init…] (or with any other collection class) returns nil? The Apple docs say that objects may return nil if allocation or initialisation fails. I don't know when initialising may fail with NSArray, but I guess that allocation may fail with insufficient memory. And because I'm developing for iOS, that may become a regular problem. Do I have to about that and check every time I want to create a new array, or will my app fail because of memory constraints (assuming worst-case situation, of course) and checking for nil is just a waste of cycles?

Currently, I'm only checking when I allocate a mutable collection with a large predetermined capacity (e.g. [NSMutableArray arrayWithCapacity: 1000]) or an immutable collection with lots of objects (over a thousand).

Thank you.

like image 812
Constantino Tsarouhas Avatar asked Apr 21 '26 02:04

Constantino Tsarouhas


1 Answers

No, not with NSArray. NSArray is a linked list using structs, so it does not malloc much behind the scenes. Checking for nil, at least with NSArray is rather pointless.

However, if you were using a collection class like CCArray, from cocos2d, for example then checking for nil with a large array could be beneficial.

Still, the size of a pointer on iOS is 8 bytes, and even a C-Array of 1000 elements is only 8 KB of RAM. In most cases, you won't be using enough memory to the point where you will run out.

Also note that if you come to the point where your application is running low on memory, there are many delegate methods that you can register to to be warned about this and fix it.

like image 82
Richard J. Ross III Avatar answered Apr 22 '26 17:04

Richard J. Ross III



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!