driis
driis

Reputation: 164301

How do i take advantage of NSCoding to convert an object into a NSDictionary ?

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

How do I make this conversion in Objective-C ?

Upvotes: 3

Views: 1966

Answers (3)

jscs
jscs

Reputation: 64002

It should be straightforward to create an NSCoder subclass, whose encode<thing>:forKey: methods just stick the things into a dictionary, which you can then retrieve.

@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 coder, and send encodeWithCoder: to this object you want in a dictionary.

Upvotes: 3

Mario
Mario

Reputation: 4520

What Andrew Madsen said. If you wanted to use NSCoding though, you would've to encode your object to an NSData object using NSKeyedArchiver an put that NSData in your dictionary. Wouldn't be human-readable though, if that is of concern. Cheers

Edit: re-reading your question, it's really what Andrew said since you want 1:1 representation of key:values in a dictionary - the NSCoding approach would give you the whole object as value for your dictionary key. So, +1 to Andrew.

Upvotes: 0

Andrew Madsen
Andrew Madsen

Reputation: 21373

NSObject has a method dictionaryWithValuesForKeys:. From the documentation:

Returns a dictionary containing the property values identified by each of the keys in a given array.

There's also a corresponding -setValuesForKeysWithDictionary: method.

NSCoding doesn't actually come in to play here.

Upvotes: 9

Related Questions