views:

100

answers:

1

I'm writing an app where support for "promotions" is required, and these promotions could be arbitrarily complex and many different pieces of data might be relevant in their calculation. Therefore, whilst in the early stages of development, I don't want to invent a whole specification schema for these things, I'd rather just write each one in Objective-C and then somehow serialize the compiled code into the (CoreData) database for later recall and execution.

Is this in any way possible? I was thinking that GCD blocks might be a good candidate for this, although I'm not aware of any out-of-the-box method for serializing / deserializing them.

Thanks for any advice.

edit: this is an iPhone app so unfortunately I can't use something like Python function pickling ... it has to be straight Objective-C ...

+1  A: 

I don't think it's possible to serialize blocks.

I would encapsulate the data into a class, and implement NSCoding protocol. E.g.

@interface Promotion :NSObject<NSCoding> {   // protocol might be better
}
-(void)calculatePromotion; 
@end

then

@interface PromotionX : Promotion {
    ... data needed for a promotion of type X ...
} 
-initWithDataA: (A*)a andDataB:(B*) b
@end

now you need to implement various things

@implementation PromotionX
-initWithDataA: (A*)a and DataB:(B*)b{
    ... save a and b to the ivars ...
}
-(void)calculatePromotion{
    ... do something with a and b 
}

#pragma mark Serialization support
-initWithCoder:(NSCoder*)coder{
    ... read off a and b from a coder ...
}
-(void)encodeWithCoder:(NSCoder*)coder{
    ... write a and b to a coder ...
}
@end

Similarly for the promotion of type Y, Z, etc. Now it can be saved into a file, or NSData, using NSKeyedArchiver. Then you can resurrect the promotion object without referring to the specific type (X,Y,Z) by

NSData* data = ... somehow get the data from the file / CoreData etc...
Promotion* promotion = [NSKeyedUnarchiver unarchiveObjectWithData:data];
[promotion calculatePromotion];

For serialization in general, read this Apple doc.

Yuji
Thanks very much for the advice, that seems like a good way to go.
glenc