iOS 的 Keychain 是一個安全的儲存容器,常用來保存帳號、密碼、認證 token 等敏感資訊。Keychain 內的資料會加密保存,即使 App 被刪除,部分資料仍可能保留,重新安裝後仍可讀取。
若要使用 Keychain,需要在 Build Phases 中加入 Security.framework。
若只需要保存簡單物件,可以自己封裝一個工具類。概念是將資料轉成 NSData,再以 kSecClassGenericPassword 存入 Keychain。
+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service {
return [NSMutableDictionary dictionaryWithObjectsAndKeys:
(id)kSecClassGenericPassword, (id)kSecClass,
service, (id)kSecAttrService,
service, (id)kSecAttrAccount,
(id)kSecAttrAccessibleAfterFirstUnlock, (id)kSecAttrAccessible,
nil
];
}
+ (BOOL)save:(NSString *)service data:(id)data {
NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
SecItemDelete((CFDictionaryRef)keychainQuery);
[keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(id)kSecValueData];
return SecItemAdd((CFDictionaryRef)keychainQuery, NULL) == noErr;
}
+ (void)delete:(NSString *)service {
NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
SecItemDelete((CFDictionaryRef)keychainQuery);
}
讀取時,會在查詢字典中加入 kSecReturnData 與 kSecMatchLimitOne,讓 Keychain 回傳一筆符合條件的資料。取得 NSData 後,再用 NSKeyedUnarchiver 還原成原本物件。
在模擬器上,每次重新執行 App 時,實際上可能會經歷卸載與重新安裝的流程。但存於 Keychain 的資料仍可能保留,因此可用來驗證持久化效果。


若需求較複雜,也可以參考 Apple 提供的 KeychainItemWrapper。其原理同樣是透過 SecItemAdd、SecItemUpdate、SecItemDelete、SecItemCopyMatching 操作 Keychain,只是封裝了更多欄位與錯誤處理。