0%

《Objective-C 编程》17.NSArray

NSArray

  • NSArray 实例可以保存一组 (指向其他对象的) 指针
  • NSArray 的实例是无法改变的。一旦 NSArray 实例被创建后,就无法添加或删除数组里的指针,也无法改变数组的指针顺序;
  • 数组是个数据容器,可以往该容器里任意添加多个对象;
  • 数组中只能存放 对象类型 , 不能存放基本数据类型;
  • 数组中存入对象的类型需要一致;
  • NSArray 中的指针是有序排列的,可以通过索引(index)存取数组中的对象;
  • 注意数组越界。

数组的创建

// 创建3个 NSDate 对象
NSDate *now = [NSDate date];
NSDate *tomorrow = [now dateByAddingTimeInterval:24.0 * 60.0 * 60.0];
NSDate *yesterday = [now dateByAddingTimeInterval:- 24.0 * 60.0 * 60.0];

// 创建一个数组包含这三个 NSDate 对象
// 1⃣️ 使用字面量语法
NSArray *dateList1 = @[now,tomorrow,yesterday];

// 2⃣️ 旧式数组方法,类方法
NSArray *dateList2 = [NSArray arrayWithObjects:now,tomorrow,yesterday, nil];

// 3⃣️ 初始化方法
NSArray *dateList3 = [[NSArray alloc] initWithObjects:now,tomorrow,yesterday, nil];

// 4⃣️ 创建数组并且往数组中存入一个元素
NSArray *dateList4 = [NSArray arrayWithObject:now];

// 5⃣️ 创建一个数组,数组中的元素来自另一个数组
NSArray *dateList5 = [NSArray arrayWithArray:dateList1];

NSArray 的常用方法

通过下标获取对象:

用来访问 NSArray 实例中指针的语句称为 下标

  • 1⃣️ 字面量语法:
NSLog(@"%@",dateList1[0]);
  • 2⃣️ objectAtIndex: 方法:
NSLog(@"%@",[dateList1 objectAtIndex:1]);

获取数组中的元素个数:count

NSUInteger count = [array count];

获取数组中某个元素,防止数组越界

/// 来自YYCategories
- (id)objectOrNilAtIndex:(NSUInteger)index {
    return index < self.count ? self[index] : nil;
}

判断数组中是否包含某一个对象

BOOL isContains = [array containsObject:@"list"];

注:如果数组中的元素都是非重复对象的话,建议使用 NSSet 来检查某个对象是否存在,因为后者的速度更快。

查找出一个对象在数组中的下标位置

NSUInteger index = [array indexOfObject:@"lisi--"];
if (index == NSNotFound) {
    NSLog(@"数组中没有此元素");
}

注:

  • - (NSUInteger)indexOfObject:(ObjectType)anObject;
  • - (NSUInteger)indexOfObjectIdenticalTo:(ObjectType)anObject;
    两者都会返回相应数组值等于给定对象的最低索引。区别在于第一个方法会枚举数组中的每一个对象并发送 isEqual: 消息(anObject 会作为实参传入),检查是否 “相等”(内容相等)。第二个方法也会枚举数组中的每一个对象,但是会用 == 运算符来和 anObject 做比较,检查是否 “相同”(是否还指向同一块内存地址)。

使用连接符将数组中的字符串拼接起来

NSString *joinString = [array componentsJoinedByString:@"-"];

将字符串分割后存进数组中

NSString *s = @"ios-Android-Windows";
NSArray *separete = [s componentsSeparatedByString:@"-"];

访问数组中最后一个元素

NSString *lastObj = [array lastObject];

追加对象,array1 追加 1 个对象,存放到 array2 中

NSArray *array2 = [array1 arrayByAddingObject:@"赵六"];

数组的遍历

NSUInteger dateCount = [dateList1 count];
for (int i = 0; i < dateCount; i++) {
   NSDate *d = dateList1[i];
   NSLog(@"Here is a date:%@",d);
}

快速枚举

提示:使用快速遍历 NSMytableArray 数组时,不能在枚举过程中增加或者删除数组中的指针。如果遍历时需要添加或删除指针,则需要使用标准的 for 循环。

for (NSDate *d in dateList1) {
    NSLog(@"Here is a date:%@",d);
}

相关阅读

  • iOS 中冷知识:NSArray

欢迎关注我的其它发布渠道