How can I use NSCoding to convert an object to an NSDictionary?

I have an Objective-C class that implements NSCoding. I need to return an instance representation of this class as NSDictionary, where keys are property names and values ​​are property values.

How to do this conversion in Objective-C?

+3
source share
3 answers

By directly creating a subclass NSCoder, the methods are encode<thing>:forKey:simply inserted thinginto the dictionary, which you can then get.

@implementation DriisDictCoder
{
    NSMutableDictionary * encodedDict;
}

- (void)encodeDouble: (double)v forKey: (NSString *)k {
    [codedDict addObject:[NSNumber numberWithDouble:v] forKey:k];
}

// etc.

// Custom method
- (NSDictionary *)dictForEncodedObject {
     return encodedDict;
}

@end

Then you create an instance of your encoder and send to encodeWithCoder:this object that you want in the dictionary.

+3
source

NSObject has a method dictionaryWithValuesForKeys:. From the documentation:

, , .

-setValuesForKeysWithDictionary:.

NSCoding .

+8

What Andrew Madsen said. If you want to use NSCoding, you will have to encode your object to an NSData object using NSKeyedArchiver and put the NSData in your dictionary. At least it would be impossible for a person if it causes concern. Greetings

Edit: re-read your question, this is really what Andrey said, because you want a 1: 1 key representation: values ​​in a dictionary - the NSCoding approach will provide you with the whole object as a value for your dictionary key. So, +1 to Andrew.

0
source

All Articles