1, archive to deal with the data type of the nsstrings, NSArrry, NSData, NSDictionary
2, data model to use archiving must achieve <NSSecureCoding,NSCoding> protocol
Take a data model for example
Save the data
If (@available(iOS 12.0,*)) {NSError *error; NSData *data = [NSKeyedArchiver archivedDataWithRootObject:token requiringSecureCoding:YES error:&error]; If (error) {NSLog(@"token failed to save %@",error); } else { [data writeToFile:[self tokenFilePath] atomically:YES]; } } else { [NSKeyedArchiver archiveRootObject:token toFile:[self tokenFilePath]]; }Copy the code
Read the data
If (@available(iOS 12.0,*)) {NSData *data = [NSData dataWithContentsOfFile:[self tokenFilePath]]; NSError *error; Token *token = [NSKeyedUnarchiver unarchivedObjectOfClass:Token.class fromData:data error:&error]; If (error) {NSLog(@"token failed to obtain %@",error); } return token; } else { Token *token = [NSKeyedUnarchiver unarchiveObjectWithFile:[self tokenFilePath]]; return token; }Copy the code
Create a sandbox path
+ (NSString *)tokenFilePath {
NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [pathDocuments stringByAppendingPathComponent:@"xxx.plist"];
return path;
}
Copy the code