简体   繁体   中英

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 (eg [NSMutableArray arrayWithCapacity: 1000] ) or an immutable collection with lots of objects (over a thousand).

Thank you.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM