NSArray 基礎
- 有序、不可變的物件集合;
- 只能儲存 Objective-C 物件(基本型別需用 NSNumber 封裝);
- 常用建構:
@[]、arrayWithObjects:(以 nil 結尾)。
常用操作速查
| 分類 | 方法 | 說明 |
| 查詢 | count | 元素數量 |
objectAtIndex: | 按索引取值 |
containsObject: | 是否包含某物件 |
indexOfObject: | 首次出現的索引 |
| 遍歷 | for (int i=0; i<cnt; i++) | 索引遍歷,知位置 |
for (id obj in array) | 快速枚舉,簡潔 |
enumerateObjectsUsingBlock: | Block 遍歷,可中途停止 |
NSMutableArray 變異操作
NSMutableArray *arr = [NSMutableArray array];
// 增
[arr addObject:@"a"];
[arr addObjectsFromArray:@[@"b", @"c"]];
[arr insertObject:@"x" atIndex:1];
// 刪
[arr removeObjectAtIndex:0];
[arr removeObject:@"b"]; // 刪除所有匹配
[arr removeObjectsInRange:NSMakeRange(0,2)];
[arr removeLastObject];
[arr removeAllObjects];
// 改
[arr replaceObjectAtIndex:1 withObject:@"new"];
[arr replaceObjectsInRange:NSMakeRange(0,2) withObjectsFromArray:@[@"a",@"b"]];
[arr exchangeObjectAtIndex:0 withObjectAtIndex:2];
// 重設整個陣列
[arr setArray:@[@"x", @"y"]];
實用技巧:字串分割與 URL 解析
NSString *url = @"https://www.baidu.com:8080/path";
NSArray *parts = [url componentsSeparatedByString:@"://"]; // ["http", "www.baidu.com:8080/path"]
NSArray *hostPort = [parts[1] componentsSeparatedByString:@":"]; // ["www.baidu.com", "8080/path"]
NSString *host = hostPort[0];
容量預分配
NSMutableArray *bigArray = [NSMutableArray arrayWithCapacity:10000];
// 減少多次擴容,提升大量插入效能