0

I am new in Objective-c. I am feeling confuse between NSArray and normal Array. Please tell me when to use NSArray and when to use normal array?

1 Answer 1

3

NSArray is an Objective-C object that stores a collection of NSObjects (such as NSString, NSNumber, NSDictionary, etc)

Example:

NSArray *myArray = @[@"String 1",@"String 2",@"String 3"];

(the above uses Objective-C literals to define an NSArray of NSStrings -- see http://clang.llvm.org/docs/ObjectiveCLiterals.html)

Objective-C is built on top of C, which also includes arrays (lowercase 'a'), which are commonly used as collections of primitive data types (such as int, char, etc), for example.

Example:

int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };

C arrays can also be used to store pointers, which could point to objects in memory, as pointed out by CRD/Jef in the comments.

Both have cases where they are useful, but the one of the common reasons to go with one or the other would be whether you need to store objects or primitives. Although as pointed out above, C arrays can handle objects, it is generally more common practice and more convenient to use NSArray to handle that.

Also, NSArray has a bunch of convenience functions (such as count and lastObject) that can help you with the data. See the Apple documentation on NSArray https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/

Note: if you need an array with a varying size, look into NSMutableArray

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

3 Comments

would you please give any example?
@jn_pdx - C style arrays can store objects, and ARC will handle them (ARC doesn't support structs and unions).
@CRD actually C arrays can hold pointers.., which being an address in memory, could be just about anything :)

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.