NSUserDefaults 是 iOS 最輕量的持久化方案,適合存放設定、標誌位、小體量的鍵值數據。它以 plist 形式存在 App 的 Library/Preferences 目錄下,讀寫極為方便,但只能存 property list 支援的類型。
NSData、NSString、NSNumber、NSDate、NSArray、NSDictionary。
若直接塞入自定義類的實例,會拋出這樣的錯誤:
Property list invalid for format (property lists cannot contain objects of type 'CFType')
解法是把自定義對象轉換成字典(或 NSData)再存——也就是做一次簡單的「編碼」。
@interface XYZToDoItem : NSObject
@property NSString *itemName;
@property BOOL completed;
@property NSDate *creationDate;
- (NSDictionary *)encodedItem;
@end
@implementation XYZToDoItem
// 把對象攤平成字典,才能寫入 UserDefaults
- (NSDictionary *)encodedItem {
return [NSDictionary dictionaryWithObjectsAndKeys:
self.itemName, @"itemName",
[NSNumber numberWithBool:self.completed], @"completed",
self.creationDate, @"creationDate",
nil];
}
@end
- (void)saveUserDefaultsOwn {
XYZToDoItem *item1 = [[XYZToDoItem alloc] init];
item1.itemName = @"Buy milk";
XYZToDoItem *item2 = [[XYZToDoItem alloc] init];
item2.itemName = @"Buy eggs";
XYZToDoItem *item3 = [[XYZToDoItem alloc] init];
item3.itemName = @"Read a book";
NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
[userdefaults setObject:[item1 encodedItem] forKey:@"item1"];
[userdefaults setObject:[item2 encodedItem] forKey:@"item2"];
[userdefaults setObject:[item3 encodedItem] forKey:@"item3"];
[userdefaults synchronize];
}
- (void)readUserDefaultsOwn {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSDictionary *dic1 = [userDefaults objectForKey:@"item1"];
XYZToDoItem *item1 = [[XYZToDoItem alloc] init];
item1.itemName = [dic1 objectForKey:@"itemName"];
item1.completed = [[dic1 objectForKey:@"completed"] boolValue];
item1.creationDate = [dic1 objectForKey:@"creationDate"];
NSDictionary *dic2 = [userDefaults objectForKey:@"item2"];
XYZToDoItem *item2 = [[XYZToDoItem alloc] init];
item2.itemName = [dic2 objectForKey:@"itemName"];
item2.completed = [[dic2 objectForKey:@"completed"] boolValue];
item2.creationDate = [dic2 objectForKey:@"creationDate"];
NSDictionary *dic3 = [userDefaults objectForKey:@"item3"];
XYZToDoItem *item3 = [[XYZToDoItem alloc] init];
item3.itemName = [dic3 objectForKey:@"itemName"];
item3.completed = [[dic3 objectForKey:@"completed"] boolValue];
item3.creationDate = [dic3 objectForKey:@"creationDate"];
[self.toDoItems addObject:item1];
[self.toDoItems addObject:item2];
[self.toDoItems addObject:item3];
}
上面是「手動攤平/還原」的示範寫法,理解原理很有幫助,但正式專案更推薦用 NSCoding 或 NSSecureCoding 把歸檔邏輯收攏進模型自身:
- (void)encodeWithCoder:(NSCoder *)coder {
[coder encodeObject:self.itemName forKey:@"itemName"];
[coder encodeBool:self.completed forKey:@"completed"];
[coder encodeObject:self.creationDate forKey:@"creationDate"];
}
- (instancetype)initWithCoder:(NSCoder *)coder {
self = [super init];
if (self) {
_itemName = [coder decodeObjectForKey:@"itemName"];
_completed = [coder decodeBoolForKey:@"completed"];
_creationDate = [coder decodeObjectForKey:@"creationDate"];
}
return self;
}
如此一來,存取端只需 NSKeyedArchiver 與 NSKeyedUnarchiver,不必為每個屬性寫一遍映射。
最後提醒界線:NSUserDefaults 適合「小數據」;若數據量大、需要查詢或關聯,應該改用 SQLite、Core Data 或檔案存儲。往 UserDefaults 塞大對象會拖慢啟動速度,也可能因 plist 寫入失敗而靜默丟失數據。