Krumelur
Krumelur

Reputation: 32597

Create NSDictionary-backed objects

I want to create a "business object" based on a NSDictionary. The reason for this is that I want implementations to be able to extend this object with arbitrary keys, and another reason is that I am persisting it using the convenient plist format (the objects stored are either integers, floats or strings).

The business object contains a number of predefined properties, e.g.

@property NSString* customerName;
@property NSString* productCode;
@property int count;
@property double unitPrice;

I want to serialize this, for example to a property list (this is not a strict requirement, it could be some other easy-to-use format). Preferably, the implementation of the class should be just

@synthesize customerName, productCode, count, unitPrice:

for the example above. To use this class, I want to do something like:

MyBusinessObject* obj = [MyBusinessObject businessObjectWithContentsOfFile:fileName];
obj.productCode = @"Example";
[obj setObject:@"Some data" forKey:@"AnExtendedProperty"];
[obj writeToFile:fileName atomically:YES];

Upvotes: 0

Views: 152

Answers (2)

Krumelur
Krumelur

Reputation: 32597

The "path of least resistance" turned out to be using NSCoding instead.

Upvotes: 0

Vignesh
Vignesh

Reputation: 10251

You should make your class KVC complaint. KVC does the magic. Look here.Ex,

   // assume inputValues contains values we want to
// set on the person

NSDictionary * inputValues;
YOURCLASS    * person = [[YOURCLASS alloc] init];

[person setValuesForKeysWithDictionary: inputValues];

Upvotes: 2

Related Questions