// Get
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString* userId = [defaults objectForKey:@"UserId"];
[defaults synchronize];
// Set
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:userId forKey:@"UserId"];
[defaults synchronize];
// Clear
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:@"UserId"];
[defaults synchronize];
Custom Object
// Get
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *formData = [defaults objectForKey:@"CustomObject"];
MyCustomData *data=[NSKeyedUnarchiver unarchiveObjectWithData:data];
[defaults synchronize];
// Set
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:myCustomObject];
[defaults setObject:data forKey:@"CustomObject"];
[defaults synchronize];
// Clear
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:@"CustomObject"];
[defaults synchronize];
1 則留言:
補充一點,如果custom class層級很深,例如A Class裡面又包B Class,且二者都為custom class,那麼A、B就都一定要實作Coding,不然會報錯 「‧‧‧‧ encodeWithCoder unrecognized selector sent to instance ‧‧‧」
張貼留言