1

With all the useful things you get from NSArray and NSMutableArray, why would you ever use a "C Style" array with Objective-C objects?

NSString *array[] = {@"dog", @"cat", @"boy"};
1
  • Further OT, is there a meta discussion of exactly this c-tag problem? I'm myself pretty grumpy about c++ and obj-c questions using the c tag. Commented Dec 23, 2011 at 2:30

2 Answers 2

5

For short, fixed arrays, the availability of a nice compact initialization syntax (as you've demonstrated) can be nice. In certain cases, a C style array may also offer a performance benefit compared to using NSArray. Another thing that comes to mind is that NSArray doesn't offer any built in support for multidimensional arrays, while multidimensional C arrays are easy.

And of course, there's the fact that you can only store objects in NSArray, not C-primitive types, but you asked specifically about using C arrays with Objective-C objects.

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

2 Comments

+1. The performance benefit can be huge, since the compiler can apply a lot of optimization, which can't be done when using NSArray, because of typical objective-c features such as categories and method swizzling, which (in theory) could alter NSArray's behavior.
Can you still use the usual C idiom sizeof(array) / sizeof(array[0]) to get the count? Could you use sizeof(array) / sizeof([array class]) ?
1

All useful things come at a price.

Ever try making an NSArray of ints? You can't. You MUST use NSNumber.

Why? Because NSArray doesn't know what to do with things it doesn't know how to memory-manage... and the only things that conform to it's memory-management requirements are things based on NSObject.

It's just one example, but there are plenty of others.

Bottom line is, there is rarely ever one single "best" answer to anything. NSArray is no exception.

Comments

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.