1.<NSCoding> ?存儲一個model
ProductModel* productModel=[[ProductModelalloc]init];
productModel.title=@"小黃人自行車";
productModel.image=@"xx";
//立馬崩潰只能存儲對象
// [[NSUserDefaults standardUserDefaults] setObject:productModel forKey:@"STORE_PRODUCT"];
//如果沒有實現(xiàn)encoding也會崩潰,會提示沒有實現(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ù)制對象。
如果自定義類具有可變和不可變的區(qū)別,就需要同時實現(xiàn)NSCopying和NSMutableCopying,在- (id)copyWithZone:(NSZone *)zone返回的是不可變對象,在- (id)mutableCopyWithZone:(NSZone *)zone返回的是可變對象。
如果 [ ?xx ?copy ]沒有實現(xiàn)copy協(xié)議。會出現(xiàn) [xx ?copyWithZone:]立馬崩潰。
ProductModel* productModel2=[productModel1 copy];
productModel2.title=@"ofo共享單車";
NSLog(@"title1:%@title2:%@",productModel1.title,productModel2.title);
NSLog(@"");