有没有什么方法来序列化/反序列化一个Objective-C块? [英] Is there any way to serialize / unserialize an Objective-C block?

查看:153
本文介绍了有没有什么方法来序列化/反序列化一个Objective-C块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个应用程序,需要支持促销,这些促销可能是任意复杂的,许多不同的数据可能与他们的计算相关。因此,虽然在开发的早期阶段,我不想为这些事情发明一个完整的规范模式,我宁愿只是写在Objective-C每一个,然后不知何故将编译的代码序列化到(CoreData)数据库以便稍后回收和执行。

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.

这是否有可能?我认为GCD块可能是一个很好的候选人,虽然我不知道任何开箱即用的方法序列化/反序列化他们。

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.

感谢您的任何建议。

编辑:这是一个iPhone应用程序,所以不幸的是我不能使用像Python函数pickling ...它必须是直的Objective- C ...

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

推荐答案

我不认为可以序列化块。

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

我会将数据封装到一个类中,并实现 NSCoding 协议。例如

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

然后

@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

类似地,对于类型Y,Z等的促销现在可以保存到文件中,或 NSData ,使用 NSKeyedArchiver
然后您可以通过

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];

对于序列化,请阅读此Apple文档

这篇关于有没有什么方法来序列化/反序列化一个Objective-C块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆