So, I'm making an iPhone app in Objective-C and need to use an array. Usually in Objective-C I'd use NSArray or NSMutableArray, but I'm starting to wonder if that's the best idea when simply using a basic array. Memory- and efficiency-wise, does it make more sense to use a regular C array or an Objective-C array when simply keeping a basica array of custom objects? And do you usually use C arrays or Objective-C arrays when programming in Objective-C? Thanks!
This really just depends on what you want to do with the array.
For arrays of numbers that you're going to do lots of math on, C arrays are probably a better choice (or at least a class that wraps C arrays). If you're constantly converting back and forth between scalars and objects and aren't using any of NSArray's more advanced features, all it will buy you is a lot of overhead.
However, Cocoa objects have a number of memory management invariants that you must obey or your app will go boom. C arrays and C++ vectors will blissfully ignore these requirements, meaning a lot more work for you to keep them in line. NSArray will take care of these for you. When you're dealing with Cocoa objects, use an NSArray.
Unless I've found a good reason to not use them, NSArray
is my de-facto choice.
And in several years of Cocoa programming, I've never really found a good reason to not use it. The only things I've been able to come up with are when then things I want to store in an array are not objects, or I want to store objects but not have them be retained. In both of those cases, however, a simple CFMutableArrayRef
with custom value callbacks does the trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With