Is there any way to serialize / unserialize an Objective-C block?

妖精的绣舞 提交于 2019-12-10 22:18:38

问题


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:


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.



来源:https://stackoverflow.com/questions/3325838/is-there-any-way-to-serialize-unserialize-an-objective-c-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!