本地數據存儲之UserDefaults
UserDefaults支持的基本數據類型包含:
NSData
, NSString
, NSNumber
, NSDate
, NSArray
, or NSDictionary
對於自定義的類,如果直接存儲會出現如下錯誤:
Property list invalid for format (property lists cannot contain objects of type ‘CFType’)
如果想存儲自定義的類,需要對其進行編碼即轉換為基本數據類型。
類定義,以及轉換為NSDictionary類型:
@interface XYZToDoItem : NSObject @property NSString *itemName; @property BOOL completed; //@property (readonly) NSDate *creationDate; @property NSDate *creationDate; - (NSDictionary *) encodedItem; @end
@implementation XYZToDoItem #pragma Used for encoded objects to be able to save to UserDeafaults - (NSDictionary *) encodedItem { return [NSDictionary dictionaryWithObjectsAndKeys:self.itemName, @itemName, [NSNumber numberWithBool:self.completed], @completed, self.creationDate , @creationDate, nil]; } @end
調用的地方,存儲如UserDefault裡,並且讀取轉換為相應的類:
- (void) saveUserDefaultsOwn { XYZToDoItem *item1 = [[XYZToDoItem alloc] init]; item1.itemName = @Buy milk; //[self.toDoItems addObject:item1]; XYZToDoItem *item2 = [[XYZToDoItem alloc] init]; item2.itemName = @Buy eggs; //[self.toDoItems addObject:item2]; XYZToDoItem *item3 = [[XYZToDoItem alloc] init]; item3.itemName = @Read a book; //[self.toDoItems addObject:item3]; 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) readUserDeafultsOwn { NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; NSDictionary *dic1 = [[NSDictionary alloc] init]; dic1 = [userDefaults objectForKey:@item1]; XYZToDoItem *item1 = [[XYZToDoItem alloc] init]; item1.itemName = [dic1 objectForKey:@itemName]; item1.completed = [dic1 objectForKey:@completed]; item1.creationDate = [dic1 objectForKey:@creationDate]; //initial it is readonly, not right dic1 = [userDefaults objectForKey:@item2]; XYZToDoItem *item2 = [[XYZToDoItem alloc] init]; item2.itemName = [dic1 objectForKey:@itemName]; item2.completed = [dic1 objectForKey:@completed]; item2.creationDate = [dic1 objectForKey:@creationDate]; //initial it is readonly, not right dic1 = [userDefaults objectForKey:@item2]; XYZToDoItem *item3 = [[XYZToDoItem alloc] init]; item3.itemName = [dic1 objectForKey:@itemName]; item3.completed = [dic1 objectForKey:@completed]; item3.creationDate = [dic1 objectForKey:@creationDate]; //initial it is readonly, not right //XYZToDoItem *item2 = [userDefaults objectForKey:@item2]; //XYZToDoItem *item3 = [userDefaults objectForKey:@item3]; [self.toDoItems addObject:item1]; [self.toDoItems addObject:item2]; [self.toDoItems addObject:item3]; }
綜上為簡單的對復雜的類進行簡單封裝並且讀取的例子。