本文對Foundation框架中的數組類(NSArray、MutableNSArray)的使用做一個詳細的總結。
1. NSArray
1. NSArray 介紹
- NSArray 是 OC 中的數組類,開發中建議盡量使用 NSArray 替代 C 語言中的數組
- C 語言中雖然也有數組,但在開發的過程中存在一些弊端
- int array[4] = {10, 89, 27, 76};
- 只能存放一種類型的數據(類型必須一致)
- 不能很方便地動態添加數組元素、不能很方便地動態刪除數組元素(長度固定)
- Foundation數組是有序的對象集合
- 一般情況下,一個數組中的元素都是一種特定類型,但不是必需的
2. NSArray 的創建方式
+ (instancetype)array;
+ (instancetype)arrayWithObject:(id)anObject;
+ (instancetype)arrayWithObjects:(id)firstObj, ...;
+ (instancetype)arrayWithArray:(NSArray *)array;
+ (id)arrayWithContentsOfFile:(NSString *)path;
+ (id)arrayWithContentsOfURL:(NSURL *)url;
3. NSArray 的使用注意事項
- NSArray直接使用NSLog()作為字符串輸出時是小括號括起來的形式。
- 只能存放任意OC對象, 并且是有順序的
- 不能存儲非OC對象, 比如int\float\double\char\enum\struct等
- NSArray中不能存儲nil,因為NSArray認為nil是數組的結束(nil是數組元素結束的標記)。nil就是0。0也是基本數據類型,不能存放到NSArray中。
- 它是不可變的,一旦初始化完畢后,它里面的內容就永遠是固定的,不能刪除里面的元素,也不能再往里面添加元素
NSArray *arr = [NSArray arrayWithObjects:@"abc", nil ,@"edf",@"hij", nil];
NSLog(@"%@", arr);
輸出結果:
(
abc
)
4. NSArray 的常用方法
// 先定義一個數組,用于舉例說明下面各個常用方法如何使用
NSArray *arr = [NSArray arrayWithObjects:@"abc",@"edf",@"hij", nil];
- 獲取集合元素個數
- (NSUInteger)count;
NSLog(@"count = %lu",[arr count]);
輸出結果:count = 3
- 獲得index位置的元素
- (id)objectAtIndex:(NSUInteger)index;
NSLog(@"arr[1] = %@",[arr objectAtIndex:1]);
輸出結果:arr[1] = edf
- 是否包含某一個元素
- (BOOL)containsObject:(id)anObject;
if ([arr containsObject:@"klm"]) {
NSLog(@"arr中包含klm");
} else {
NSLog(@"arr中不包含klm");
}
輸出結果:arr中不包含klm
- 返回第一個元素
- (id)firstObject;
NSLog(@"first = %@",[arr firstObject]);
輸出結果:first = abc
- 返回最后一個元素
- (id)lastObject;
NSLog(@"last = %@",[arr lastObject]);
輸出結果:last = hij
- 查找anObject元素在數組中的位置(如果找不到,返回-1)
- (NSUInteger)indexOfObject:(id)anObject;
NSLog(@"index = %lu",[arr indexOfObject:@"hij"]);
輸出結果:index = 2
- 在range范圍內查找anObject元素在數組中的位置
- (NSUInteger)indexOfObject:(id)anObject inRange:(NSRange)range;
NSRange range = {1,2};
NSLog(@"index = %lu",[arr indexOfObject:@"edf" inRange:range]);
輸出結果:index = 1
5. NSArray 的簡寫形式
- 自從2012年開始,Xcode的編譯器多了很多自動生成代碼的功能,使得OC代碼更加精簡
- 之前數組的創建方式
[NSArray arrayWithObjects:@"Jack", @"Rose", @"Jim", nil];
- 現在數組的創建方式
@[@"Jack", @"Rose", @"Jim"];
- 之前數組元素的訪問方式
[array objectAtIndex:index];
- 現在數組元素的訪問方式
array[index];
6. NSArray 遍歷
1.NSArray的下標遍歷
NSArray *arr = @[@"abc", @"edf", @"hij"];
for (int i = 0; i < arr.count; ++i) {
NSLog(@"arr[%i] = %@", i, arr[i]);
}
輸出結果:
arr[0] = abc
arr[1] = edf
arr[2] = hij
2. NSArray 的快速遍歷
NSArray *arr = @[@"abc", @"edf", @"hij"];
// OC數組可以使用OC中的增強for循環來遍歷
// 逐個取出arr中的元素,將取出的元素賦值給obj
// 注意:obj的類型可以根據數組中元素的類型來寫,不一定要寫NSObject
for (NSString *obj in arr) {
NSLog(@"obj = %@", obj);
}
輸出結果:
obj = abc
obj = edf
obj = hij
3. NSArray 使用 block 進行遍歷
NSArray *arr = @[@"abc", @"edf", @"hij"];
// 使用OC數組的迭代器來遍歷
// 每取出一個元素就會調用一次block
// 每次調用block都會將當前取出的元素和元素對應的索引傳遞給我們
// obj就是當前取出的元素, idx就是當前元素對應的索引
[arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if (idx == 1) {
*stop = YES; // stop用于控制什么時候停止遍歷
}
NSLog(@"obj = %@, idx = %lu", obj, idx);
}];
輸出結果:
obj = abc, idx = 0
obj = edf, idx = 1
4. NSArray 給所有元素發消息
- 讓集合里面的所有元素都執行aSelector這個方法
- (void)makeObjectsPerformSelector:(SEL)aSelector;
- (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(id)argument;
// 讓數組中所有對象執行這個方法
// 注意:如果數組中的對象沒有這個方法會報錯,需要實現該方法
// [arr makeObjectsPerformSelector:@selector(say)];
[arr makeObjectsPerformSelector:@selector(eat:) withObject:@"bread"];
7. NSArray 排序
1. NSArray 排序
- Foundation自帶類排序
- 使用compare方法對數組中的元素進行排序, 那么數組中的元素必須是Foundation框架中的對象, 也就是說不能是自定義對象
NSArray *arr = @[@10,@9,@1,@19];
NSLog(@"排序前: %@", arr);
NSArray *newArr = [arr sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"排序后: %@", newArr);
輸出結果:
排序前: (
10,
9,
1,
19
)
排序后: (
1,
9,
10,
19
)
- 自定義類排序
定義一個Person類,Person擁有age屬性。
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, assign) int age;
@end
因為不能使用compare:方法對自定義對象進行排序,我們通過執行區塊block對自定義類進行排序,下面是按照age的大小對Person進行排序
Person *p1 = [Person new];
p1.age = 10;
Person *p2 = [Person new];
p2.age = 20;
Person *p3 = [Person new];
p3.age = 5;
Person *p4 = [Person new];
p4.age = 7;
NSArray *arr = @[p1, p2, p3, p4];
NSLog(@"排序前: %@", arr);
// 按照人的年齡進行排序
// 該方法默認會按照升序排序
NSArray *newArr = [arr sortedArrayWithOptions:NSSortStable usingComparator:^NSComparisonResult(Person *obj1, Person *obj2) {
// 每次調用該block都會取出數組中的兩個元素給我們
return obj1.age > obj2.age; // 升序
// return obj1.age < obj2.age; // 降序
}];
NSLog(@"排序后: %@", newArr);
輸出結果:
排序前: (
"age = 10",
"age = 20",
"age = 5",
"age = 7"
)
排序后: (
"age = 5",
"age = 7",
"age = 10",
"age = 20"
)
8. NSArray 文件讀寫
1. NSArray 數據寫入到文件中
NSArray *arr = @[@"abc", @"def", @"hij", @"klm"];
BOOL flag = [arr writeToFile:@"/Users/Walkers/Desktop/test.plist" atomically:YES];
NSLog(@"flag = %i", flag);
輸出結果:flag = 1
2. 從文件中讀取數據到 NSArray 中
NSArray *newArr = [NSArray arrayWithContentsOfFile:@"/Users/Walkers/Desktop/test.plist"];
NSLog(@"newArr = %@", newArr);
輸出結果:
newArr = (
abc,
def,
hij,
klm
)
9. NSArray 與字符串之間的轉換
1. 把數組元素鏈接成字符串
- 用 separator 作拼接符將數組元素拼接成一個字符串
- (NSString *)componentsJoinedByString:(NSString *)separator;
NSArray *arr = @[@"abc", @"edf", @"hij", @"klm"];
NSString *res = [arr componentsJoinedByString:@"*"];
NSLog(@"res = %@", res);
輸出結果:res = abc*edf*hij*klm
2. 字符串分割方法
- 將字符串用 separator 作為分隔符切割成數組元素
- (NSArray *)componentsSeparatedByString:(NSString *)separator;
NSString *str = @"abc-edf-hij-klm";
NSArray *arr = [str componentsSeparatedByString:@"-"];
NSLog(@"arr = %@", arr);
輸出結果:
arr = (
abc,
edf,
hij,
klm
)
2. NSMutableArray
1. NSMutableArray 介紹
- NSMutableArray是NSArray的子類
- NSArray是不可變的,一旦初始化完畢后,它里面的內容就永遠是固定的,不能刪除里面的元素,也不能再往里面添加元素
- NSMutableArray是可變的,數組元素的個數未指定并且可以根據需要增長,隨時可以往里面添加\更改\刪除元素
2. NSMutableArray 基本用法
- 創建空數組
NSMutableArray *arr = [NSMutableArray array];
- 創建數組,并且指定長度為5,此時也是空數組
NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:5];
- 創建一個數組,包含兩個元素
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"1",@"2", nil];
- 調用對象方法創建數組
NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:@"1",@"2", nil];
- 添加一個元素
- (void)addObject:(id)object;
NSMutableArray *arr = [NSMutableArray array];
[arr addObject:@"abc"];
NSLog(@"%@",arr);
輸出結果:
(
abc
)
- 添加otherArray的全部元素到當前數組中
- (void)addObjectsFromArray:(NSArray *)array;
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"abc", nil];
[arr addObjectsFromArray:@[@"def",@"hij"]];
NSLog(@"%@",arr);
輸出結果:
(
abc,
def,
hij
)
- 在index位置插入一個元素
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"abc", @"hij",nil];
[arr insertObject:@"def" atIndex:1];
NSLog(@"%@",arr);
輸出結果:
(
abc,
def,
hij
)
- 刪除最后一個元素
- (void)removeLastObject;
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"abc",@"def",@"hij",nil];
[arr removeLastObject];
NSLog(@"%@",arr);
輸出結果:
(
abc,
def
)
- 刪除所有的元素
- (void)removeAllObjects;
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"abc",@"def",@"hij",nil];
[arr removeAllObjects];
NSLog(@"%@",arr);
輸出結果:
(
)
- 刪除index位置的元素
- (void)removeObjectAtIndex:(NSUInteger)index;
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"abc",@"def",@"hij",nil];
[arr removeObjectAtIndex:1];
NSLog(@"%@",arr);
輸出結果:
(
abc,
hij
)
- 刪除特定的元素
- (void)removeObject:(id)object;
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"abc",@"def",@"hij",nil];
[arr removeObject:@"abc"];
NSLog(@"%@",arr);
輸出結果:
(
def,
hij
)
- 刪除range范圍內的所有元素
- (void)removeObjectsInRange:(NSRange)range;
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"abc",@"def",@"hij",nil];
NSRange range = NSMakeRange(1, 2);
[arr removeObjectsInRange:range];
NSLog(@"%@",arr);
輸出結果:
(
abc
)
- 用anObject替換index位置對應的元素
- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"abc",@"def",@"hij",nil];
[arr replaceObjectAtIndex:1 withObject:@"xyz"];
NSLog(@"%@",arr);
輸出結果:
(
abc,
xyz,
hij
)
- 交換idx1和idx2位置的元素
- (void)exchangeObjectAtIndex:(NSUInteger)idx1 withObjectAtIndex:(NSUInteger)idx2;
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"abc",@"def",@"hij",nil];
[arr exchangeObjectAtIndex:0 withObjectAtIndex:2];
NSLog(@"%@",arr);
輸出結果:
(
hij,
def,
abc
)
3. NSMutableArray 錯誤用法
- 不可以使用@[]創建可變數組
NSMutableArray *array = @[@"lnj", @"lmj", @"jjj"];
// 報錯, 本質還是不可變數組
[array addObject:@“Peter”];