iOS - EncodeWithCoder - Encode Nil
Asked Answered
H

2

9

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
}
Hildebrandt answered 18/5, 2014 at 2:25 Comment(0)
S
7
- (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.)

Structuralism answered 18/5, 2014 at 2:26 Comment(0)
B
14

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.

Barbitone answered 21/5, 2015 at 18:27 Comment(1)
Note that this will overwrite the old value of _duration with nil, which may not be desirable. That is, you might want to encode the value only if it's present in order to preserve an older value.Structuralism
S
7
- (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.)

Structuralism answered 18/5, 2014 at 2:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.