您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

Objective-C 陣列方法大全:NSArray 與 NSMutableArray 常用 API 整理

編輯:iOS 相關資訊

以下以這個範例陣列為基準,把 NSArray 與 NSMutableArray 的常用方法依功能分類整理。

NSArray *array = [NSArray arrayWithObjects:@"wendy", @"andy", @"tom",
                  @"jonery", @"stany", nil];

一、建立陣列

+ (id)array;                                              // 空陣列
+ (id)arrayWithObject:(id)anObject;                       // 單一元素
+ (id)arrayWithObjects:(id)firstObj, ... NS_REQUIRES_NIL_TERMINATION;  // 多元素,以 nil 結尾
+ (id)arrayWithArray:(NSArray *)array;                    // 由另一個陣列複製
+ (id)arrayWithObjects:(const id [])objects count:(NSUInteger)cnt;     // 由 C 陣列建立
+ (id)arrayWithContentsOfFile:(NSString *)path;           // 由 plist 檔讀入
+ (id)arrayWithContentsOfURL:(NSURL *)url;                // 由 URL 讀入(可為網路位置)

init 版本與上述一一對應:initWithObjects:count:、initWithObjects:、initWithArray:、initWithContentsOfFile:、initWithContentsOfURL:。另外 initWithArray:copyItems: 可以指定是否對元素做複製(YES 時每個元素都會被 copy)。

注意 arrayWithObjects:count: 的 count 不可超過 C 陣列的實際長度,否則會讀到越界記憶體。

現代寫法建議直接使用字面語法,更簡潔也更難出錯:

NSArray *array = @[@"wendy", @"andy", @"tom"];
id first = array[0];          // 取代 objectAtIndex:
array[0] = @"newValue";       // NSMutableArray 專用,取代 replaceObjectAtIndex:withObject:

二、查詢與存取

- (NSUInteger)count;                                  // 元素數量
- (id)objectAtIndex:(NSUInteger)index;                // 取出指定下標的元素
- (id)objectAtIndexedSubscript:(NSUInteger)idx;       // 同上,支援 array[idx] 語法
- (id)firstObject;                                    // 第一個元素
- (id)lastObject;                                     // 最後一個元素,空陣列回傳 nil
- (BOOL)containsObject:(id)anObject;                  // 是否包含該元素
- (NSUInteger)indexOfObject:(id)anObject;             // 回傳下標,找不到回傳 NSNotFound
- (NSUInteger)indexOfObject:(id)anObject inRange:(NSRange)range;  // 限定搜尋範圍
- (BOOL)isEqualToArray:(NSArray *)otherArray;         // 長度與各位置元素都相同才算相等

indexOfObject: 系列內部使用 isEqual: 做比較,這意味著自訂類別若要正確參與比對,必須正確覆寫 isEqual: 與 hash。indexOfObjectIdenticalTo: 則是比指標位址,也就是判斷「是不是同一個物件」。

三、切割、串接與轉字串

- (NSArray *)subarrayWithRange:(NSRange)range;        // 取出子陣列
- (NSArray *)arrayByAddingObject:(id)anObject;        // 回傳加上新元素後的新陣列
- (NSArray *)arrayByAddingObjectsFromArray:(NSArray *)otherArray;
- (NSString *)componentsJoinedByString:(NSString *)separator;
- (void)getObjects:(id[])objects range:(NSRange)range; // 把範圍內元素填入 C 陣列
- (NSArray *)objectsAtIndexes:(NSIndexSet *)indexes;   // 依索引集合取出元素

注意 arrayByAddingObject: 不改變原陣列,而是回傳一個新物件——NSArray 是不可變的,這類「add」方法都不會就地修改。

NSArray *a = @[@"wendy", @"andy", @"tom", @"jonery", @"stany", @"張三", @"asdta"];
NSRange range = NSMakeRange(1, 5);

id *objects = malloc(sizeof(id) * range.length);
[a getObjects:objects range:range];
for (NSUInteger i = 0; i < range.length; i++) {
    NSLog(@"%@", objects[i]);
}
free(objects);   // 別忘了釋放

componentsJoinedByString: 的結果:

[array componentsJoinedByString:@","];
// wendy,andy,tom,jonery,stany

description 會產生類似 Objective-C 物件描述的格式,等同 Java 的 toString,常用於除錯輸出。descriptionWithLocale: 與 descriptionWithLocale:indent: 則提供在地化與縮排版本。

四、排序

排序有四種主要寫法,彈性由低到高:

// 1. 用 selector,comparator 必須回傳 NSComparisonResult
- (NSArray *)sortedArrayUsingSelector:(SEL)comparator;

可直接傳入 NSString 現成的比較方法,例如 localizedCompare:、caseInsensitiveCompare:、localizedStandardCompare::

NSArray *arr = @[@"test", @"abc", @"xyz"];
arr = [arr sortedArrayUsingSelector:@selector(localizedCompare:)];
// 結果:abc, test, xyz
// 2. 用 C 函式指標
- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator
                              context:(void *)context;

// 3. 同上但多帶一個 hint 參數,可提升效能
- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator
                              context:(void *)context
                                 hint:(NSData *)hint;

// 4. 用 Block(最推薦)
- (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr;
- (NSArray *)sortedArrayWithOptions:(NSSortOptions)opts
                   usingComparator:(NSComparator)cmptr;

C 函式版本的比較函式:

NSInteger sortType(id st, id str, void *cha)
{
    NSString *s1 = (NSString *)st;
    NSString *s2 = (NSString *)str;

    if (s1.length > s2.length)      return NSOrderedAscending;
    else if (s1.length < s2.length) return NSOrderedDescending;
    return NSOrderedSame;
}

NSArray *a = [array sortedArrayUsingFunction:sortType context:nil];

Block 版本寫起來清爽得多:

NSArray *te = [array sortedArrayUsingComparator:^NSComparisonResult(NSString *s, NSString *s2){
    if (s.length < s2.length) return NSOrderedAscending;
    if (s.length > s2.length) return NSOrderedDescending;
    return NSOrderedSame;
}];

// 指定穩定排序
NSArray *test = [array sortedArrayWithOptions:NSSortStable
                             usingComparator:^NSComparisonResult(NSString *s, NSString *s2){
    return [s compare:s2];
}];

sortedArrayHint 會先產生一個 NSData 形式的排序提示,帶進 sortedArrayUsingFunction:context:hint: 可以減少比較次數,對已知部分有序的大量資料有明顯效果。

五、寫入檔案

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile;
- (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)atomically;

atomically 為 YES 時會先寫入暫存檔再搬移,確保不會寫到一半被中斷而產生半損檔案。要注意這種寫法只支援 plist 能表達的型別(NSString、NSNumber、NSData、NSDate、陣列、字典),自訂物件會失敗。

六、遍歷

// 前向枚舉器
NSEnumerator *enu = [array objectEnumerator];
id obj;
while (obj = enu.nextObject) {
    NSLog(@"obj===%@===", obj);
}

// 反向枚舉器
NSEnumerator *rev = [array reverseObjectEnumerator];

Block 版本更簡潔,而且可以中途停止:

[array enumerateObjectsUsingBlock:^(id str, NSUInteger index, BOOL *stop) {
    NSLog(@"%@,%d", str, index);
    if ([str isEqualToString:@"tom"]) *stop = YES;   // 提前結束
}];

// 反向遍歷
[array enumerateObjectsWithOptions:NSEnumerationReverse
                       usingBlock:^(id str, NSUInteger index, BOOL *stop) {
    NSLog(@"%@,%d", str, index);
}];

// 只遍歷指定索引集合
[array enumerateObjectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1, 3)]
                         options:NSEnumerationReverse
                      usingBlock:^(id str, NSUInteger index, BOOL *stop) {
    NSLog(@"%@,%d", str, index);
}];

stop 是 out-only 參數,只該由你在 Block 內設為 YES,不要嘗試讀它。

七、以條件搜尋

NSInteger index = [array indexOfObjectPassingTest:^BOOL(id tr, NSUInteger index, BOOL *stop){
    return [[(NSString *)tr] isEqualToString:@"wendy"];
}];

// 指定遍歷方向
[array indexOfObjectWithOptions:NSEnumerationReverse passingTest:^BOOL(id o, NSUInteger i, BOOL *s){
    return [[(NSString *)o] isEqualToString:@"andy"];
}];

// 取出所有符合條件的索引集合
NSIndexSet *index = [array indexesOfObjectsPassingTest:^BOOL(id tr, NSUInteger index, BOOL *stop){
    return [[(NSString *)tr] isEqualToString:@"andy"];
}];

另有 indexesOfObjectsWithOptions:passingTest: 與 indexesOfObjectsAtIndexes:options:passingTest: 兩個變體。

八、對元素逐一呼叫方法

- (void)makeObjectsPerformSelector:(SEL)aSelector;
- (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(id)argument;
[array makeObjectsPerformSelector:@selector(tttttt)];

前提是陣列元素的型別都實作了該方法,否則會拋出 unrecognized selector 例外。

九、NSMutableArray 專屬方法

+ (id)arrayWithCapacity:(NSUInteger)numItems;
- (id)initWithCapacity:(NSUInteger)numItems;

- (void)addObject:(id)anObject;
- (void)addObjectsFromArray:(NSArray *)otherArray;
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;
- (void)insertObjects:(NSArray *)objects atIndexes:(NSIndexSet *)indexes;

- (void)removeLastObject;
- (void)removeObjectAtIndex:(NSUInteger)index;
- (void)removeObject:(id)anObject;
- (void)removeObjectsInArray:(NSArray *)otherArray;
- (void)removeObjectsInRange:(NSRange)range;
- (void)removeObjectsAtIndexes:(NSIndexSet *)indexes;
- (void)removeAllObjects;

- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
- (void)replaceObjectsInRange:(NSRange)range withObjectsFromArray:(NSArray *)otherArray;
- (void)replaceObjectsAtIndexes:(NSIndexSet *)indexes withObjects:(NSArray *)objects;

- (void)exchangeObjectAtIndex:(NSUInteger)idx1 withObjectAtIndex:(NSUInteger)idx2;

- (void)sortUsingFunction:(NSInteger (*)(id, id, void *))compare context:(void *)context;
- (void)sortUsingSelector:(SEL)comparator;
- (void)sortUsingComparator:(NSComparator)cmptr;
- (void)sortWithOptions:(NSSortOptions)opts usingComparator:(NSComparator)cmptr;

removeObject: 系列有個「identical」變體(removeObjectIdenticalTo:),差別在於前者用 isEqual: 比較、後者比指標位址。而 removeObjectsFromIndices:numIndices: 已被標記為 deprecated,請改用 removeObjectsAtIndexes:。

arrayWithCapacity: 的參數只是效能提示,並不限制最終容量,傳入 0 完全合法。

實務提醒

第一,mutableCopy 與 copy 的差異值得記住:對 NSMutableArray 送 copy 會得到不可變的淺拷貝,送 mutableCopy 會得到可變的深拷貝(元素本身仍是共享的)。

第二,在快速枚舉(for-in)或 Block 遍歷期間修改 NSMutableArray 會拋出「collection was mutated while being enumerated」例外。若確實需要在遍歷中刪除元素,應先 mutableCopy 一份再操作,或先收集要刪的索引,迴圈結束後一次處理。

第三,多執行緒同時讀寫同一個 NSMutableArray 是不安全的。跨執行緒共享時請加上 serial queue 或 @synchronized 保護。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved