1.<NSCoding> ?存儲(chǔ)一個(gè)model
ProductModel* productModel=[[ProductModelalloc]init];
productModel.title=@"小黃人自行車";
productModel.image=@"xx";
//立馬崩潰只能存儲(chǔ)對(duì)象
// [[NSUserDefaults standardUserDefaults] setObject:productModel forKey:@"STORE_PRODUCT"];
//如果沒(méi)有實(shí)現(xiàn)encoding也會(huì)崩潰,會(huì)提示沒(méi)有實(shí)現(xiàn)encodeWithCoder
NSData*data=[NSKeyedArchiverarchivedDataWithRootObject:productModel];
[[NSUserDefaultsstandardUserDefaults]setObject:dataforKey:@"STORE_PRODUCT"];
NSData*unData = [[NSUserDefaultsstandardUserDefaults]objectForKey:@"STORE_PRODUCT"];
ProductModel* unProductModel=[NSKeyedUnarchiverunarchiveObjectWithData:unData];
NSLog(@"title:%@",unProductModel.title);
- (nullableinstancetype)initWithCoder:(NSCoder*)aDecoder
{
self= [superinit];
if(self)
{
self.title= [aDecoderdecodeObjectForKey:@"title"];
self.image=[aDecoderdecodeObjectForKey:@"image"];
}
returnself;
}
- (void)encodeWithCoder:(NSCoder*)aCoder
{
[aCoderencodeObject:self.titleforKey:@"title"];
[aCoderencodeObject:self.imageforKey:@"image"];
}
2.<NSCopy> ?復(fù)制對(duì)象。
如果自定義類具有可變和不可變的區(qū)別玫膀,就需要同時(shí)實(shí)現(xiàn)NSCopying和NSMutableCopying,在- (id)copyWithZone:(NSZone *)zone返回的是不可變對(duì)象漠吻,在- (id)mutableCopyWithZone:(NSZone *)zone返回的是可變對(duì)象蝌数。
如果 [ ?xx ?copy ]沒(méi)有實(shí)現(xiàn)copy協(xié)議哩盲。會(huì)出現(xiàn) [xx ?copyWithZone:]立馬崩潰艰管。
ProductModel* productModel2=[productModel1 copy];
productModel2.title=@"ofo共享單車";
NSLog(@"title1:%@title2:%@",productModel1.title,productModel2.title);
NSLog(@"");