iOS can use the Nskeyedarchiver class to serialize objects to NSData stored on disk, provided that the class to which the object belongs must comply with the Nscoding protocol.
The Nscoding protocol contains two methods, and the classes to be serialized must implement them
-(void) Encodewithcoder: (nscoder *) Acoder;//Serialize data encode (encode data)
-(nullable instancetype) Initwithcoder: (nscoder *) Adecoder; //Deserialize data decode (decodes data)
Cases:
@interface myentity:nsobject<nscoding>
@property (nonatomic, strong) NSString *name;
@end
@implementation myentity
-(void) Encodewithcoder: (nscoder *) acoder {
[ACoder.encodeObject:self.name forkey:@ "name"];
}
-(instancetype) Initwithcoder: (nscoder *) adecoder {
[self.name = adecoder.decodeobjectforkey:@ "name"];
}
@end
At this point, the Myentity class can be serialized, and the serialization process:
myentity *myentity = [[Myentity alloc] init];
NSData *myentitydata = [Nskeyedarchiver archiveddatawithrootobject:myentity];
[[Nsuserdefaults Standarduserdefatults] setobject:myentitydata forkey:@ "Myentitydatakey"];
Deserialization process:
NSData *myentitydataondisk = [[Nsuserdefaults standarduserdefaults] objectforkey:@ "Myentitydatakey"];
myentity *myentityondisk = [Nskeyedunarchiver Unarchiveobjectwithdata:myentitydataondisk];
IOS data serialization, Nscoding, Nscoder