NSUserDefaults, object archiving, nsuserdefaults Archiving
NSUserDefaults
@ Interface Person: NSObject <NSCoding>
@ Property (nonatomic, assign) NSInteger ID;
@ Property (nonatomic, copy) NSString * name;
@ End
// Save
NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
[User setInteger: ID forKey: @ "ID"];
[User setObject: name forKey: @ "name"];
[User synchronize];
// Obtain
NSInteger uId = [[[NSUserDefaults standardUserDefaults] integerValueForKey: @ "ID"];
NSString * name = [[NSUserDefaults standardUserDefaults] stringForKey: @ "name"];
Access by Object
// Save
[User setObject: self forKey: @ "user"];
[User synchronize];
// Obtain
User * u = [UserObjectForKey "@" user "];
2. Object Archiving
To use Object archiving, the Object must implement the NSCoding protocol. Most Object C objects comply with the NSCoding protocol. You can also implement the NSCoding protocol in custom objects. To implement the NSCoding Protocol, two methods are implemented:
-(Void) encodeWithCoder :( NSCoder *) encoder;
-(Void) initWithCoder :( NSCoder *) encoder.
At the same time, it is recommended that the object also implement the NSCopying protocol, which allows copying objects. To implement the NSCopying protocol, the-(id) copyWithZone :( NSZone *) zone method must be implemented.
@ Interface Person: NSObject <NSCoding>
@ Property (nonatomic, assign) NSInteger ID;
@ Property (nonatomic, copy) NSString * name;
@ End
@ Implementation User
// The following two methods must be implemented, otherwise crash will be called
-(Void) encodeWithCoder :( NSCoder *) ACO;
{
// Put the attributes that need to be persisted here
[Ecoder encodeObject: [NSNumber numberWithInteger: self. ID] forKey: @ "ID"];
[Ecoder encodeObject: self. name forKey: @ "name"];
}
-(Id) initWithCoder :( NSCoder *) aDecoder
{
If (self = [self init])
{
// It must be consistent with the content in the encodeWithCoder method. Otherwise, no data can be read.
Self. userID = [[aDecoder decodeObjectForKey: @ "ID"] integerValue];
Self. name = [aDecoder decodeObjectForKey: @ "name"];
}
Return self;
}
// Usage
+ (BOOL) save {
NSError * error = nil;
// Determine the storage path, usually the file under the Document directory
NSString * fileName = [self getFileName];
NSString * filePath = [self getFilePath];
If (! [[NSFileManager defaultManager] createDirectoryAtPath: filePath withIntermediateDirectories: YES attributes: nil error: & error]) {
NSLog (@ "failed to create user file directory ");
Return NO;
}
Return [NSKeyedArchiver archiveRootObject: self toFile: [fileName: userId];
}
@ End