问题
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:
NSArray
is an Objective-C object that stores a collection of NSObject
s (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
来源:https://stackoverflow.com/questions/27874283/what-is-difference-between-nsarray-and-normal-array