您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS Foundation 框架(二):NSString 與三大集合類完整總結

編輯:iOS 開發綜合

Foundation 裡最常用的幾個類別:NSString、NSArray、NSSet、NSDictionary,以及它們各自的子類 NSMutableString、NSMutableArray、NSMutableSet、NSMutableDictionary。命名規則很一致——父類不可變,子類可變,而子類繼承父類後自然能用父類的所有方法。此外還有 NSDate、NSObject 等基礎類別。

一、NSString 的操作

用物件初始化方法建立

// 無參數
NSString *str2 = [[NSString alloc] initWithString:@"Jack"];

// 帶格式參數
NSString *str3 = [[NSString alloc] initWithFormat:@"age is %d", 10];

// C 字串 → OC 字串
NSString *str4 = [[NSString alloc] initWithUTF8String:"Rose"];

// OC 字串 → C 字串
const char *c = [str4 UTF8String];

// 讀取檔案(指定路徑)
NSString *str5 = [[NSString alloc] initWithContentsOfFile:@"/Users/apple/Desktop/getWeather.xml"
                                                 encoding:NSUTF8StringEncoding
                                                    error:nil];

// 讀取檔案(指定 URL)
// 本地:file://  網路:https://  伺服器:ftp://
NSURL *url = [[NSURL alloc] initWithString:@"file:///Users/apple/Desktop/getWeather.xml"];
NSString *str6 = [[NSString alloc] initWithContentsOfURL:url
                                                encoding:NSUTF8StringEncoding
                                                   error:nil];

用類方法建立

NSString *str2 = [NSString stringWithString:@"Jack"];
NSString *str3 = [NSString stringWithFormat:@"age is %d", 10];
NSString *str4 = [NSString stringWithUTF8String:"Rose"];

NSString *str5 = [NSString stringWithContentsOfFile:@"/Users/apple/Desktop/getWeather.xml"
                                           encoding:NSUTF8StringEncoding
                                              error:nil];

NSURL *url = [NSURL URLWithString:@"file:///Users/apple/Desktop/getWeather.xml"];
NSString *str6 = [NSString stringWithContentsOfURL:url
                                          encoding:NSUTF8StringEncoding
                                             error:nil];

同一功能有物件方法與類方法兩種寫法,而類方法更簡潔(且由 autorelease pool 管理,不必操心釋放),因此實務上推薦用類方法。使用中文內容時,編碼一律指定 NSUTF8StringEncoding。

把字串寫入檔案

// 寫入前會先清空原檔案內容
[@"Java,iOS" writeToFile:@"/Users/apple/Desktop/getWeather.xml"
              atomically:YES
                encoding:NSUTF8StringEncoding
                   error:nil];

NSString *content = @"iOS,Java";
NSURL *url = [NSURL fileURLWithPath:@"/Users/apple/Desktop/getWeather.xml"];
[content writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:nil];

atomically:YES 的意思是先寫到暫存檔再改名,寫入失敗時原檔不會被破壞。除非確定要追求效能,否則建議保持為 YES。

二、NSMutableString 的操作

可變與不可變的本質差異,在拼接字串時看得最清楚:

NSString *str  = [NSString stringWithFormat:@"My age is 10 "];
NSString *str2 = [str stringByAppendingString:@"11 12"];
NSLog(@"%@", str2);   // My age is 10 11 12(str 本身沒變,str2 是新物件)

NSMutableString *mutStr = [NSMutableString stringWithFormat:@"My age is 10 "];
[mutStr appendString:@"11 12"];   // 無回傳值,直接在自身後面接上
NSLog(@"%@", mutStr);  // My age is 10 11 12

刪除內容有兩種方式:

// 方式一:自己算 location 與 length(不推薦,位置一改就錯)
// [mutStr deleteCharactersInRange:NSMakeRange(13, 2)];

// 方式二:先取得範圍再刪除
NSRange range = [mutStr rangeOfString:@"11"];
[mutStr deleteCharactersInRange:range];
NSLog(@"%@", mutStr);   // My age is 10  12

三、OC 集合類的共通特性

  • NSArray、NSSet、NSDictionary 都是物件導向的集合,不像 C 陣列只能放同一種資料型別。但它們只能放 OC 物件,基本型別如 int、struct、enum 必須先包裝成 NSNumber、NSValue。
  • 集合以物件形式存在,宣告時變數前要加 *。
  • 不可變與否在建立時就決定,而且終身不變——想要「把不可變陣列轉成可變」只能重新建立一個新的。

NSArray 的基本操作

// 建立
NSArray *array1 = [NSArray arrayWithObjects:@"Jack", @"Rose", nil];  // nil 是結束標記
NSArray *array2 = @[@"Jack", @"Rose"];                                // 推薦語法

// 長度
NSUInteger count = [array1 count];

// 取值(兩種寫法)
NSString *a = [array1 objectAtIndex:0];
NSString *b = array1[0];   // 編譯器特性,本質等同上一行

注意 arrayWithObjects: 以 nil 作為結束標記,這也代表 OC 陣列不能存放 nil。若需要「空值」語意,改用 NSNull。

三種遍歷方式

// 1. 索引 for 迴圈,可用 break 中途離開
for (int i = 0; i < array1.count; i++) {
    NSLog(@"%@", array1[i]);
    if (i == 0) break;
}

// 2. 快速枚舉
for (id obj in array1) {
    NSUInteger index = [array1 indexOfObject:obj];
    NSLog(@"%ld-->%@", index, obj);
}

// 3. Block 枚舉,可透過 stop 提前結束
[array1 enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSLog(@"%ld-->%@", idx, obj);
    if (idx == 0) {
        *stop = YES;
    }
}];

第三種方式在需要同時拿到索引與物件、或想在特定條件下跳出時最方便。要注意 Block 內對 self 的使用可能造成循環引用,這時候要用 __weak 打破。

NSMutableArray 的基本操作

NSMutableArray *mutableArray = [NSMutableArray array];
// 注意:@[] 產生的是不可變 NSArray,不能直接指定給可變變數

Person *person = [[Person alloc] init];
[mutableArray addObject:person];
[mutableArray addObject:@"Jack"];
[mutableArray addObject:@"John"];
// [mutableArray addObject:10];   // 錯:不能放基本型別

[mutableArray removeObject:@"John"];
[mutableArray removeObjectAtIndex:0];
[mutableArray removeAllObjects];

四、NSSet 與 NSMutableSet

NSSet *set2 = [NSSet setWithObjects:@"Jack", @"Rose", @"Jim", nil];
NSString *str = [set2 anyObject];   // 隨機取一個

NSMutableSet *mutableSet = [NSMutableSet set];
[mutableSet addObject:@"Jack"];
[mutableSet addObject:@"Rose"];
[mutableSet removeObject:@"Jack"];

NSArray 與 NSSet 的對照

  • 兩者都能放任意 OC 物件、都不能放基本型別、本身都不可變而子類可變。
  • NSArray 有序,NSSet 無序。這是選擇時最關鍵的差異。
  • NSSet 的強項是 containsObject: 的查詢速度接近常數時間,且天生處理重複元素。實務上若你需要「去重」或「大量存在性判斷」,用 NSSet;若順序對使用者有意義(例如列表顯示),用 NSArray。

五、NSDictionary 與 NSMutableDictionary

字典以 key/value 成對存在,本身不可變且無序。key 若重複,後者會覆蓋前者;value 則允許重複。

// 建立方式一:空字典
NSDictionary *dic = [NSDictionary dictionary];

// 方式二:一組 key/value
NSDictionary *dic1 = [NSDictionary dictionaryWithObject:@"Jack" forKey:@"name"];

// 方式三:以陣列批次指定
NSArray *keys   = @[@"name", @"address", @"e-mail"];
NSArray *values = @[@"Jack", @"北京", @"jack@163.com"];
NSDictionary *dic3 = [NSDictionary dictionaryWithObjects:values forKeys:keys];

// 方式四:交錯排列
NSDictionary *dic4 = [NSDictionary dictionaryWithObjectsAndKeys:
                      @"Jack", @"name",
                      @"北京", @"address",
                      @"jack@163.com", @"e-mail", nil];

// 方式五:字面語法(推薦)
NSDictionary *dic5 = @{@"name": @"Jack",
                       @"address": @"北京",
                       @"e-mail": @"jack@163.com"};

// 取值與長度
NSString *name = [dic1 objectForKey:@"name"];
NSUInteger cnt = dic5.count;

遍歷字典

// 方式一:先取全部 key(順序不定)
NSArray *allKeys = [dic5 allKeys];
for (int i = 0; i < dic5.count; i++) {
    NSString *key = allKeys[i];
    NSLog(@"%@-->%@", key, dic5[key]);
}

// 方式二:Block 直接拿到 key 與 value
[dic5 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    NSLog(@"%@-->%@", key, obj);
    *stop = YES;
}];

NSMutableDictionary 的基本操作

NSMutableDictionary *mutableDic = [NSMutableDictionary dictionary];
// 注意:@{...} 右邊回傳的是不可變字典,不能指定給可變變數

[mutableDic setObject:@"Rose" forKey:@"name"];
[mutableDic setObject:@"北京" forKey:@"address"];

[mutableDic removeObjectForKey:@"name"];
[mutableDic removeAllObjects];

NSLog(@"%@", mutableDic);   // address = "\U5317\U4eac"; name = Rose;

輸出中的 \U5317\U4eac 就是「北京」的 UTF-16 轉義表示,這是 description 方法的正常行為,不是亂碼。

六、綜合範例:用集合組出通訊錄

NSArray *friends = @[
    @{@"name": @"張三", @"phone": @"13993214321", @"address": @"北京"},
    @{@"name": @"李斯", @"phone": @"13498766789", @"address": @"上海"},
    @{@"name": @"王武", @"phone": @"15898766789", @"address": @"天津"},
    @{@"name": @"趙柳", @"phone": @"18798766789", @"address": @"南京"}
];

// 取出「李斯」的資料
NSDictionary *dic = friends[1];
NSLog(@"%@", dic);

這個「陣列裝字典」的組合是 iOS 開發中最常見的資料結構,特別是在處理 JSON 回應時——最外層陣列對應列表,每個字典對應一筆紀錄。理解它的嵌套關係,是後續做 Model 轉換的基礎。

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