简体   繁体   中英

iOS - EncodeWithCoder - Encode Nil

I have an object that has a property that might be nil. How should I implement this in encodeWithCoder (and decodeWithCoder)?

- (void)encodeWithCoder:(NSCoder *)aCoder
{ 
    [aCoder encodeObject:_duration forKey:kDuration]; //_duration could be nil
}

Aaron's solution is clean and clearly communicates what's going on. I couldn't find any information, however, whether it's OK to pass nil to encodeObject:forKey: , so I tested it. It turns out that you can safely do so (please correct me if I'm missing something).

So you can simply say

- (void)encodeWithCoder:(NSCoder *)aCoder
{ 
    [aCoder encodeObject:_duration forKey:kDuration]; //_duration could be nil
}

Even when _duration is nil, this will work. It will simply not write the key to the coder in that case.

- (void)encodeWithCoder:(NSCoder *)aCoder
{ 
    if (_duration) {
        [aCoder encodeObject:_duration forKey:kDuration]; //_duration could be nil
    }
}

(Your object will be nil on decode if the key is not present.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM