前言
@interface NSArray<__covariant ObjectType> : NSObject <NSCopying, NSMutableCopying, NSSecureCoding, NSFastEnumeration>
@interface NSMutableArray<ObjectType> : NSArray<ObjectType>
数组只能存储 OC 对象,不能存储 C 语言中的基本数据类型,也不能存储 nil 。
-
Xcode 7 对系统中常用的一系列容器类型都增加了泛型支持(),有了泛型后就可以指定容器类中对象的类型了。假如向泛型容器中加入错误的对象,编译器会报警告。
__covariant:协变性,子类型可以强转到父类型(里氏替换原则)。 __contravariant:逆变性,父类型可以强转到子类型。
不指定泛型类型的对象可以和任意泛型类型转化,但指定了泛型类型后,两个不同类型间是不可以强转的,假如你希望主动控制转化关系,就需要使用泛型的协变性和逆变性修饰符。
1、不可变数组 NSArray 的创建
// 直接创建不可变数组
/*
数组成员是 id 类型,表示数组元素可以是任意的 oc 对象。
*/
NSArray *arr1 = @[@"bei", @"jing", @"huan", @"ying", @"nin"];
// 对象方法创建
NSArray *arr2 = [[NSArray alloc] init];
// 和 arr1 的地址不相同
NSArray *arr3 = [[NSArray alloc] initWithArray:arr1];
NSArray *arr4 = [[NSArray alloc] initWithObjects:@"bei", @"jing", @"huan", @"ying", @"nin", nil];
// 类方法创建
NSArray *arr5 = [NSArray array];
// 和 arr1 的地址不相同
NSArray *arr6 = [NSArray arrayWithArray:arr1];
// 创建只有一个元素(id)的数组
NSArray *arr7 = [NSArray arrayWithObject:@"qian"];
NSArray *arr8 = [NSArray arrayWithObjects:@"bei", @"jing", @"huan", @"ying", @"nin", nil];
// 从 文件 创建字符串
NSString *path = [NSHomeDirectory() stringByAppendingString:@"/Desktop/test.txt"];
NSArray *arr9 = [[NSArray alloc] initWithContentsOfFile:path];
NSArray *arr10 = [NSArray arrayWithContentsOfFile:path];
// 从 Url 创建字符串
/*
file:// 文件前缀
*/
NSURL *url = [NSURL URLWithString:[@"file://" stringByAppendingString:[NSHomeDirectory()
stringByAppendingString:@"/Desktop/test.txt"]]];
NSArray *arr11 = [[NSArray alloc] initWithContentsOfURL:url];
NSArray *arr12 = [NSArray arrayWithContentsOfURL:url];
// 泛型定义
// 指明数组中存放的是 NSString 类型数据
NSArray<NSString *> *arr13 = @[@"bei", @"jing", @"huan", @"ying", @"nin"];
// 指明数组中存放的是 NSNumber 类型数据
NSArray<NSNumber *> *arr14 = @[@2, @4, @6, @8, @10];
2、数组成员个数计算
NSArray *arr = @[@"bei", @"jing", @"huan", @"ying", @"nin"];
NSUInteger length = [arr count];
3、从数组中取成员
NSArray *arr = @[@"bei", @"jing", @"huan", @"ying", @"nin"];
// []
NSArray *arr1 = arr[1];
// objectAtIndex
NSArray *arr2 = [arr objectAtIndex:2];
// subarrayWithRange
NSArray *arr3 = [arr subarrayWithRange:NSMakeRange(2, 2)];
// for...in 循环
/*
取出数组中的每个元素,分别保存在 tmp 中
*/
for (NSString *tmp in arr) {
NSLog(@"%@", tmp);
}
// id (void *) 泛型指针, 取出数组中的每个元素,分别保存在 tmp 中
for (id tmp in arr) {
NSLog(@"tmp = %@", tmp);
}
4、取数组中最后一个元素
NSArray *arr = @[@"bei", @"jing", @"huan", @"ying", @"nin"];
id lastObject1 = [arr lastObject];
id lastObject2 = arr[[arr count]-1];
5、由元素的值获取下标
NSArray *arr = @[@"bei", @"jing", @"huan", @"ying", @"nin"];
NSUInteger index = [arr indexOfObject:@"huan"];
6、判断数组中是否包含某个元素
NSArray *arr = @[@"bei", @"jing", @"huan", @"ying", @"nin"];
BOOL result = [arr containsObject:@"huan"];
7、数组的比较
NSArray *arr1 = @[@"bei", @"jing", @"huan", @"ying", @"nin"];
NSArray *arr2 = @[@"ni", @"hao", @"bei", @"jing"];
// isEqualToArray
// 比较两个数组内容是否相同
BOOL bl = [arr1 isEqualToArray:arr2];
// firstObjectCommonWithArray
// 返回两个数组中第一个相同的元素
NSString *str = [arr1 firstObjectCommonWithArray:arr2];
8、数组组合
NSArray *arr1 = @[@"bei", @"jing", @"huan", @"ying", @"nin"];
NSArray *arr2 = @[@"Users", @"JHQ0228", @"Desktop"];
// 按指定字符组合
NSString *str1 = [arr1 componentsJoinedByString:@" "];
// 按路径组合
/*
将数组中的元素自动组合成路径,在每个元素之间自动加上 “/”
*/
NSString *str2 = [NSString pathWithComponents:arr2];
9、可变数组 NSMutableArray 的创建
// 对象方法创建
/*
创建指定长度的数组,预先分配空间,提高效率,实际长度可大于指定长度
*/
NSMutableArray *arr1 = [[NSMutableArray alloc] initWithCapacity:0];
// 类方法创建
/*
创建指定长度的数组,预先分配空间,提高效率,实际长度可大于指定长度
*/
NSMutableArray *arr2 = [NSMutableArray arrayWithCapacity:0];
10、数组元素的添加
NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
// addObject
// 向数组中追加一个元素
[arr addObject:@"bei"];
// addObjectsFromArray
// 追加数组
NSArray *arrAdd = @[@"dian", @"ying", @"xue", @"yuan"];
[arr addObjectsFromArray:arrAdd];
// insertObject... atIndex
// 在数组中任意位置插入一个元素
[arr insertObject:@"hao" atIndex:2];
// arrayByAddingObject
// 向数组添加一个元素,返回一个新的数组
NSArray *arr1 = [arr arrayByAddingObject:@"ma"];
11、数组元素的删除
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"nan", @"jing", @"huan", @"ying",
@"nin", @"bei", @"jing", @"ni", @"hao", nil];
// 删除指定下标的元素
[arr removeObjectAtIndex:2];
// 删除指定元素,删除所有指定元素
[arr removeObject:@"ying"];
// 删除指定元素
[arr removeObjectIdenticalTo:@"nan"];
// 删除指定范围的元素
NSRange range = {2,1};
[arr removeObjectsInRange:range];
// 删除最后一个元素
[arr removeLastObject];
// 删除所有元素
[arr removeAllObjects];
12、数组元素的替换
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"nan", @"jing", @"hao", nil];
// 替换指定下标元素
[arr replaceObjectAtIndex:1 withObject:@"ren"];
13、数组元素的交换
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"bei", @"jing", @"nin", @"hao", nil];
[arr exchangeObjectAtIndex:0 withObjectAtIndex:1];
14、数组元素的修改
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"bei", @"jing", @"nin", @"hao", nil];
// 修改整个数组(覆盖重写)
[arr setArray:@[@"bei", @"jing", @"huan", @"ying", @"nin"]];
// 修改数组中的某个元素
arr[3] = @"huan";
15、给数组里的所有元素发送一个消息
Student *stu1 = [[Student alloc] init];
Student *stu2 = [[Student alloc] init];
Student *stu3 = [[Student alloc] init];
NSArray *arr = [NSArray arrayWithObjects:stu1, stu2, stu3, nil];
// 发送消息
[arr makeObjectsPerformSelector:@selector(studentTest)];
16、数组的遍历
-
用 for 循环遍历
NSArray * array = [NSArray arrayWithObjects:@"bei", @"jing", @"huan", @"ying", @"nin", nil]; for (int i = 0; i < [array count]; i ++) { NSLog(@"%@", array[i]); }
-
用 for...in 循环遍历
NSArray *array = [NSArray arrayWithObjects:@"bei", @"jing", @"huan", @"ying", @"nin", nil]; // id (void *) 泛型指针, 取出数组中的每个元素,分别保存在 tmp 中 for (id tmp in array) { NSLog(@"%@", tmp); } // 取出数组中的每个元素,分别保存在 tmp 中 for (NSString *tmp in array) { NSLog(@"%@", tmp); }
-
用 block 循环遍历
NSArray *array = [NSArray arrayWithObjects:@"bei", @"jing", @"huan", @"ying", @"nin", nil]; [array enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { // obj == array[i],idx == i NSLog(@"%@", obj); if ([obj isEqual: @"huan"]) { // 停止遍历 *stop = YES; } }];
-
用迭代器遍历
NSArray *array = [NSArray arrayWithObjects:@"bei", @"jing", @"huan", @"ying", @"nin", nil]; // 获取数组的正序迭代器 NSEnumerator *enu1 = [array objectEnumerator]; // 获取数组的反序迭代器 NSEnumerator *enu2 = [array reverseObjectEnumerator]; id obj = nil; // 正序,获取下一个需要遍历的元素 while (obj = [enu1 nextObject]) { NSLog(@"%@", obj); } // 反序,获取下一个需要遍历的元素 while (obj = [enu2 nextObject]) { NSLog(@"%@", obj); }
-
条件遍历
// 1.indexesOfObjectsPassingTest NSArray *array = [NSArray arrayWithObjects:@3, @8, @17, @2, @25, @6, @89, nil]; NSIndexSet *indexSet = [array indexesOfObjectsPassingTest:^BOOL(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { // 遍历数组,找出数组中所有大于 10 的元素的位置 return [obj intValue] > 10 ? : NO; }]; [indexSet enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) { // 输出所有大于 10 的元素值 NSLog(@"%@", array[idx]); }]; // 2.indexOfObjectPassingTest NSUInteger index = [array indexOfObjectPassingTest:^BOOL(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { // 遍历数组,找出数组中第一个大于 10 的元素的位置 return [obj intValue] > 10 ? : NO; }]; // 输出第一个大于 10 的元素值 NSLog(@"%@", array[index]);
17、数组排序
-
冒泡排序
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"sunday", @"sunny", @"summer", @"sun", nil]; for (int i = 0; i < [arr count] - 1; i++) { for (int j = 0; j < [arr count] - 1 - i; j++) { // 大小判断 arr[j] > arr[j + 1] if ([arr[j] compare:arr[j + 1]] == NSOrderedDescending) { // 位置交换 [arr exchangeObjectAtIndex:j withObjectAtIndex:(j + 1)]; } } }
-
用指定的方法排序
// 1.用指定的方法排序,可变数组排序 NSMutableArray *arr1 = [NSMutableArray arrayWithObjects:@"sunday", @"sunny", @"summer", @"sun", nil]; // 原数组的顺序改变,指定元素的比较方法:compare:,默认排序方式为升序排列 [arr1 sortUsingSelector:@selector(compare:)]; // 使排序结果 降序 排列 NSEnumerator *enu = [arr1 reverseObjectEnumerator]; id obj = nil; while (obj = [enu nextObject]) { // 排序后的结果为降序 NSLog(@"%@", obj); } // 2.用指定的方法排序,不可变数组排序 NSArray *arr2 = [NSArray arrayWithObjects:@"sunday", @"sunny", @"summer", @"sun", nil]; // 返回一个排好的数组,原数组的顺序不变,指定元素的比较方法:compare: NSArray *arr3 = [arr2 sortedArrayUsingSelector:@selector(compare:)]; // 3.用指定的方法排序,自定义类 // People.h #import <Foundation/Foundation.h> @interface People : NSObject // 名 @property (nonatomic, retain) NSString *firstname; // 姓 @property (nonatomic, retain) NSString *lastname; + (id)peopleWithFirstname:(NSString *)firstname lastname:(NSString *)lastname; // 返回值类型为 NSComparisonResult - (NSComparisonResult)comparePeople:(People *)peop; @end // People.m #import "People.h" @implementation People + (id)peopleWithFirstname:(NSString *)firstname lastname:(NSString *)lastname { People * peop = [[People alloc] init]; peop.lastname = lastname; peop.firstname = firstname; return peop; } - (NSComparisonResult)comparePeople:(People *)peop { // 先按照姓排序 NSComparisonResult result = [self.lastname compare: peop.lastname]; if (result == NSOrderedSame) { // 如果有相同的姓,就比较名字 result = [self.firstname compare: peop.firstname]; } return result; } -(NSString *)description{ return [NSString stringWithFormat:@"%@ %@", self.firstname, self.lastname]; } @end // main.m #import "People.h" People *peop1 = [People peopleWithFirstname:@"MingJie" lastname:@"Li"]; People *peop2 = [People peopleWithFirstname:@"LongHu" lastname:@"Huang"]; People *peop3 = [People peopleWithFirstname:@"LianJie" lastname:@"Li"]; People *peop4 = [People peopleWithFirstname:@"Jian" lastname:@"Xiao"]; // 1.用指定的方法排序,可变数组排序 NSMutableArray *array1 = [NSMutableArray arrayWithObjects:peop1, peop2, peop3, peop4, nil]; // 原数组的顺序改变 [array1 sortUsingSelector:@selector(comparePeople:)]; // 2.用指定的方法排序,不可变数组排序 NSArray *array2 = [NSArray arrayWithObjects:peop1, peop2, peop3, peop4, nil]; // 返回一个排好的数组,原数组的顺序不变 NSArray *array3 = [array2 sortedArrayUsingSelector:@selector(comparePeople:)];
-
用 Block 排序
// 1.利用 block 进行排序,可变数组排序 NSMutableArray *arr1 = [NSMutableArray arrayWithObjects:@"sunday", @"sunny", @"summer", @"sun", nil]; [arr1 sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) { // 指定比较的方法,两个元素值比较 NSComparisonResult result = [obj1 compare:obj2]; // 返回比较的结果 return result; }]; // 2.利用 block 进行排序,不可变数组排序 NSArray *arr2 = [NSArray arrayWithObjects:@"sunday", @"sunny", @"summer", @"sun", nil]; // 返回一个排好的数组 NSArray *arr3 = [arr2 sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) { // 指定比较的方法,两个元素值比较 NSComparisonResult result = [obj1 compare:obj2]; // 返回比较的结果 return result; }]; // 3.利用 block 进行排序,自定义类 // People1.h #import <Foundation/Foundation.h> @interface People1 : NSObject // 名 @property (nonatomic, retain) NSString *firstname; // 姓 @property (nonatomic, retain) NSString *lastname; + (id)peopleWithFirstname:(NSString *)firstname lastname:(NSString *)lastname; @end // People1.m #import "People1.h” @implementation People1 + (id)peopleWithFirstname:(NSString *)firstname lastname:(NSString *)lastname { People1 * peop = [[People1 alloc] init]; peop.lastname = lastname; peop.firstname = firstname; return peop; } -(NSString *)description{ return [NSString stringWithFormat:@"%@ %@", self.firstname, self.lastname]; } @end // main.m #import "People1.h” People1 *peop1 = [People1 peopleWithFirstname:@"MingJie" lastname:@"Li"]; People1 *peop2 = [People1 peopleWithFirstname:@"LongHu" lastname:@"Huang"]; People1 *peop3 = [People1 peopleWithFirstname:@"LianJie" lastname:@"Li"]; People1 *peop4 = [People1 peopleWithFirstname:@"Jian" lastname:@"Xiao"]; // 1.利用 block 进行排序,可变数组排序 NSMutableArray *array1 = [NSMutableArray arrayWithObjects:peop1, peop2, peop3, peop4, nil]; [array1 sortUsingComparator:^NSComparisonResult(People1 * _Nonnull obj1, People1 * _Nonnull obj2) { // 先按照姓排序 NSComparisonResult result = [obj1.lastname compare:obj2.lastname]; if (result == NSOrderedSame) { // 如果有相同的姓,就比较名字 result = [obj1.firstname compare:obj2.firstname]; } return result; }]; // 2.利用 block 进行排序,不可变数组排序 NSArray *array2 = [NSArray arrayWithObjects:peop1, peop2, peop3, peop4, nil]; NSArray *array3 = [array2 sortedArrayUsingComparator:^NSComparisonResult(People1 * _Nonnull obj1, People1 * _Nonnull obj2) { // 先按照姓排序 NSComparisonResult result = [obj1.lastname compare:obj2.lastname]; if (result == NSOrderedSame) { // 如果有相同的姓,就比较名字 result = [obj1.firstname compare:obj2.firstname]; } return result; }];
-
按描述器排序
// Book.h #import <Foundation/Foundation.h> @interface Book : NSObject @property (nonatomic, retain) NSString *name; + (id)bookWithName:(NSString *)name; @end // Book.m #import "Book.h" @implementation Book + (id)bookWithName:(NSString *)name { Book *book = [[Book alloc] init]; book.name = name; return book; } @end // People2.h #import <Foundation/Foundation.h> @class Book; @interface People2 : NSObject // 名 @property (nonatomic, retain) NSString *firstname; // 姓 @property (nonatomic, retain) NSString *lastname; // 书 @property (nonatomic, retain) Book *book; + (id)peopleWithFirstname:(NSString *)firstname lastname:(NSString *)lastname bookName:(NSString *)bookName; @end // People2.m #import "People2.h" #import "Book.h" @implementation People2 + (id)peopleWithFirstname:(NSString *)firstname lastname:(NSString *)lastname bookName:(NSString *)bookName { People2 *peop = [[People2 alloc] init]; peop.lastname = lastname; peop.firstname = firstname; peop.book = [Book bookWithName:bookName]; return peop; } - (NSString *)description{ return [NSString stringWithFormat:@"%@ %@, bookName: %@", self.firstname, self.lastname, self.book.name]; } @end // main.m #import "People2.h" People2 *peop1 = [People2 peopleWithFirstname:@"MingJie" lastname:@"Li" bookName:@"book1"]; People2 *peop2 = [People2 peopleWithFirstname:@"LongHu" lastname:@"Huang" bookName:@"book2"]; People2 *peop3 = [People2 peopleWithFirstname:@"LianJie" lastname:@"Li" bookName:@"book2"]; People2 *peop4 = [People2 peopleWithFirstname:@"Jian" lastname:@"Xiao" bookName:@"book1"]; // 先按照书名进行排序 /* 这里的 key 写的是 @property 的名称 */ NSSortDescriptor *bookNameDesc = [NSSortDescriptor sortDescriptorWithKey:@"book.name" ascending:YES]; // 再按照姓进行排序 NSSortDescriptor *lastnameDesc = [NSSortDescriptor sortDescriptorWithKey:@"lastname" ascending:YES]; // 再按照名进行排序 NSSortDescriptor *firstnameDesc = [NSSortDescriptor sortDescriptorWithKey:@"firstname" ascending:YES]; // 1.按描述器排序,可变数组排序 NSMutableArray *array1 = [NSMutableArray arrayWithObjects:peop1, peop2, peop3, peop4, nil]; // 按顺序添加排序描述器 NSMutableArray *descs1 = [NSMutableArray arrayWithObjects:bookNameDesc, lastnameDesc, firstnameDesc, nil]; [array1 sortUsingDescriptors:descs1]; // 2.按描述器排序,不可变数组排序 NSArray *array2 = [NSArray arrayWithObjects:peop1, peop2, peop3, peop4, nil]; // 按顺序添加排序描述器 NSArray *descs2 = [NSArray arrayWithObjects:bookNameDesc, lastnameDesc, firstnameDesc, nil]; NSArray *array3 = [array2 sortedArrayUsingDescriptors:descs2];