不少时候咱们都须要将对象序列化,好比将一个对象存入到NSUserDefault 里面去的时候,因为NSUserDefault支持存入的类型有限制,因此不少时候咱们须要将NSObject类型的对象转换成NSData再存入进去。 spa
- (id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; if (self) { self.country = [aDecoder decodeObjectForKey:@"country"]; self.city = [aDecoder decodeObjectForKey:@"city"]; self.region = [aDecoder decodeObjectForKey:@"region"]; self.street = [aDecoder decodeObjectForKey:@"street"]; self.location = [aDecoder decodeObjectForKey:@"location"]; } return self; } - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:_country forKey:@"country"]; [aCoder encodeObject:_city forKey:@"city"]; [aCoder encodeObject:_region forKey:@"region"]; [aCoder encodeObject:_street forKey:@"street"]; [aCoder encodeObject:_location forKey:@"location"]; }
当你要进行对象拷贝的时候须要遵循NSCopy协议 code
- (id)copyWithZone:(NSZone *)zone { id copy = [[[self class] alloc] init]; if (copy) { [copy setId:[self.id copyWithZone:zone]]; [copy setNickName:[self.nickName copyWithZone:zone]]; } return copy; }