《Objective-C 編程》17.NSArray

  • NSArray 實例可以保存一組 (指向其他對象的) 指針
  • NSArray 的實例是無法改變的。一旦 NSArray 實例被創建后,就無法添加或刪除數組里的指針, 也無法改變數組的指針順序;
  • NSArray數組是個數據容器,可以往該容器里任意添加多個對象;
  • NSArray數組中只能存放對象類型,不能存放基本數據類型
  • NSArray數組中存入對象的類型需要一致;
  • NSArray 中的指針是有序排列的,可以通過索引(index)存取數組中的對象;
  • 注意數組越界問題。

NSArray 的常用方法

數組的創建

// 創建 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 實例中指針的語句稱為下標

  • 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:@"-"];

NSStringNSArray 的相互轉換:

NSArray *dataSourceArray = @[@"[https://test1.jpg](https://test1.jpg)",
                             @"[https://test2.jpg](https://test2.jpg)",
                             @"[https://test3.jpg](https://test3.jpg)"];

// NSArray -> NSString
NSString *imageString = [dataSourceArray componentsJoinedByString:@","];
// @"[https://test1.jpg,https://test2.jpg,https://test3.jpg](https://test1.jpg,https://test2.jpg,https://test3.jpg)"

// NSString -> NSArray
NSArray *imagesArray = [imageString componentsSeparatedByString:@","];
// @[@"[https://test1.jpg](https://test1.jpg)",@"[https://test2.jpg](https://test2.jpg)",@"[https://test3.jpg](https://test3.jpg)"]

訪問數組中最后一個元素

NSString *lastObj = [array lastObject];

追加對象,array1追加1個對象,存放到array2中

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

數組的遍歷

1.使用傳統的 for 循環來遍歷數組

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

2.快速枚舉法(for-in)

快速枚舉(fast enumeration)是一種簡化的 for 循環語法,它能夠過高效地遍歷數組中的所有元素。使用快速枚舉省去了對數組計數的麻煩。

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

?? 當使用快速枚舉法遍歷 NSMytableArray 類型的數組時,不能在枚舉過程中增加或者刪除數組中的指針。如果遍歷時需要添加或刪除指針,則需要使用標準的 for 循環。

3.基于 Block 對象的枚舉法

推薦使用基于 block 的枚舉方法:

- (void)enumerateObjectsUsingBlock:(void (NS_NOESCAPE ^)(ObjectType obj, NSUInteger idx, BOOL *stop))block;
- (void)enumerateObjectsWithOptions:(NSEnumerationOptions)opts usingBlock:(void (NS_NOESCAPE ^)(ObjectType obj, NSUInteger idx, BOOL *stop))block;
- (void)enumerateObjectsAtIndexes:(NSIndexSet *)s options:(NSEnumerationOptions)opts usingBlock:(void (NS_NOESCAPE ^)(ObjectType obj, NSUInteger idx, BOOL *stop))block;

示例代碼:

NSArray *array;
[array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    // Do something with 'object'
    if (shouldStop) {
        *stop = YES;
    }
}];
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容