What is difference between NSArray and normal Array?

心已入冬 提交于 2019-12-13 07:16:44

问题


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 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



来源:https://stackoverflow.com/questions/27874283/what-is-difference-between-nsarray-and-normal-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!