Persistence Method for saving custom type objects in OC
In OC, if you want to save a custom-type object to a file, you must perform the following three conditions: if you want to persistently store custom-type arrays (that is, to write temporary data in the memory to the disk in the form of a file <database, etc.>), the following conditions must be met: 1. custom objects must be serialized (storing data in an orderly manner. archive is required for persistence. if a persistent file needs to be loaded, deserialization is required (that is, the data stored in sequence is read and changed to a custom object) the first step is to serialize the custom type and the third step. File deserialization must implement the <NSCoding> protocol in OC. Taking the Student Class As An Example
@interface Student : NSObject<NSCoding>@property(nonatomic,copy)NSString * name;@property(nonatomic,copy)NSString * pwd;@end
The serialization method is
-(void)encodeWithCoder:(NSCoder *)aCoder{ [aCoder encodeObject:self.name forKey:@"name"]; [aCoder encodeObject:self.pwd forKey:@"pwd"];}
The deserialization method is as follows:
-(id)initWithCoder:(NSCoder *)aDecoder{ self= [super init]; if(self) { self.name=[aDecoder decodeObjectForKey:@"name"]; self.pwd=[aDecoder decodeObjectForKey:@"pwd"]; } return self;}
Note that we do not need to declare these two files in the Declaration file of the class, because we only use these two methods in this class, therefore, we only need to implement these two methods in the implementation file. It is worth noting that the archive operation is implemented by the system when the two methods of this Protocol are implemented outside, so we do not need to implement the archive operation. All we need is to write the file to the specified file and read the file. We can understand that serialization and deserialization are implemented in the process of implementing read and write methods. The archive operation is implemented. The code for writing and reading files is as follows:
[NSKeyedArchiver archiveRootObject:stuArr toFile:@"/Users/Administrator/Desktop/4.plist"]; [NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/Administrator/Desktop/4.plist"];
Traverse the objects contained in the file to obtain all the attributes of the objects contained in the file.
for(Student * s in stuArr) { NSLog(@"%@,%@",s.name,s.pwd); }