NSCoding和NSCopy

不少時候咱們都須要將對象序列化,好比將一個對象存入到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;
}
相關文章
相關標籤/搜索