iOS之Object-C基础编程之NSArray和NSMutableArray

官方说明:An array (NSArray) is used to represent an ordered list of objects. The only requirement is that each item be an Objective-C object—there’s no requirement for each object to be an instance of the same class.

To maintain order in the array, each element is stored at a zero-based index.

   关键词:有序的Object-C对象,从0开始索引。

   文档

   基本介绍和操作:Objective-C语法之NSArray和NSMutableArray

   注意:NSArray是以nil为结束标识。如果你的某个对象为nil,那么后面的对象将不会添加到数组中。

   比如:

   id firstObject = @"someString";
   id secondObject = nil;
   id thirdObject = @"anotherString";
   NSArray *someArray =
  [NSArray arrayWithObjects:firstObject, secondObject, thirdObject, nil];

   推荐字面量写法:

  NSArray *someArray = @[firstObject, secondObject, thirdObject];
      

   读取时可以使用下标:id data = someArray[0];
   这样写的好处是不会添加nil对象到数组中,如果对象为nil时,会在初始化时抛出异常,更早的发现问题。

        id firstObject = @"Some";
        id secondObject = nil;
        id thirdObject = @1;
        //下面这行代码不会崩溃,但数组大小为2,
        NSArray *someArray = [NSArray arrayWithObjects:firstObject,secondObject ,thirdObject, nil];
        //初始化就会崩溃
//        NSArray *someArray = @[firstObject,secondObject,thirdObject];






    


你可能感兴趣的:(iOS之Object-C基础编程之NSArray和NSMutableArray)