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

I am writing an application in which support for "promotions" is required, and these promotions can be arbitrarily complex, and many different pieces of data can be significant in their calculations. Therefore, although in the early stages of development I do not want to come up with a whole specification scheme for these things, I would just write each of them in Objective-C, and then somehow serialize the compiled code to a database (CoreData) for later recall and execution.

Is it possible? I thought GCD blocks might be a good candidate for this, although I don't know which of the ready-made methods to serialize / deserialize them.

Thanks for any advice.

edit: this is an iPhone app, so unfortunately I can't use something like etching a Python function ... it should be direct Objective-C ...

+3
source share
1 answer

I don’t think blocks can be serialized.

I would encapsulate the data in a class and implement the protocol NSCoding. For instance.

@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 promoting types Y, Z, etc. Now it can be saved to a file or NSDatausing NSKeyedArchiver. Then you can resurrect the promo object without referring to a specific type (X, Y, Z) on

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 document .

+4

Source: https://habr.com/ru/post/1756342/


All Articles