oc中的NSCoding和NSCopy

作者: shaneZhang 分类: ios技术 发布时间: 2014-06-24 17:12

很多时候我们都需要将对象序列化,比如将一个对象存入到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;
}

如果觉得我的文章对您有用,请随意打赏。如果有其他问题请联系博主QQ(909491009)或者下方留言!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注