3

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

13 Comments

@jrturton I think you meant to comment on my question. Yes, I realise now how pointless it is, but I think my intentions are nevertheless clear. I edited the question. :-p
NSArray is an object class (actually a cluster of classes behind the scenes). An array may be backed by a linked list, or it may be backed by a C array or some other collection—it's an implementation detail that's deliberately hidden from you.
1000 8-byte elements is 8 kilobytes, not 8 megabytes.
@H2CO3 [NSArray new] is pointless because NSArray is immutable. It cannot be changed, so its just an empty array, which is better described by nil.
@RichardJ.RossIII: an empty set is not the same as a null pointer. There are legitimate situations where one needs to distinguish (e.g. "valid-but-empty data" vs. "invalid data.")
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.