NSCoding和NSCopy

很多时候我们都需要将对象序列化,比如将一个对象存入到NSUserDefault 里面去的时候,由于NSUserDefault支持存入的类型有限制,所以很多时候我们需要将NSObject类型的对象转换成NSData再存入进去。

- (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协议

- (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;
}




你可能感兴趣的:(NSCoding和NSCopy)