NSArray 和普通数组有什么区别? [英] What is difference between NSArray and normal Array?
问题描述
我是 Objective-c 的新手.我对 NSArray 和普通 Array 感到困惑.请问什么时候用NSArray,什么时候用普通数组?
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?
推荐答案
NSArray
是一个 Objective-C 对象,用于存储 NSObject
的集合(例如 NSString
、NSNumber
、NSDictionary
等)
NSArray
is an Objective-C object that stores a collection of NSObject
s (such as NSString
, NSNumber
, NSDictionary
, etc)
示例:
NSArray *myArray = @[@"String 1",@"String 2",@"String 3"];
(以上使用 Objective-C 文字来定义 NSStrings
的 NSArray
-- 请参阅 http://clang.llvm.org/docs/ObjectiveCLiterals.html)
(the above uses Objective-C literals to define an NSArray
of NSStrings
-- see http://clang.llvm.org/docs/ObjectiveCLiterals.html)
Objective-C 建立在 C 之上,其中还包括数组(小写的 'a'),它们通常用作原始数据类型(例如 int
、char
等),例如.
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.
示例:
int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
C 数组也可用于存储指针,这些指针可以指向内存中的对象,正如 CRD/Jef 在注释中指出的那样.
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.
两者都有有用的情况,但选择其中一个的常见原因之一是您是否需要存储对象或原语.虽然如上所述,C 数组可以处理对象,但通常使用 NSArray
来处理它是更常见的做法,也更方便.
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.
此外,NSArray
有一堆方便的函数(例如 count
和 lastObject
)可以帮助您处理数据.请参阅关于 NSArray
的 Apple 文档 https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/
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/
注意:如果你需要一个不同大小的数组,查看NSMutableArray
Note: if you need an array with a varying size, look into NSMutableArray
这篇关于NSArray 和普通数组有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!