3

我正在编写一个需要支持“促销”的应用程序,这些促销可能非常复杂,并且许多不同的数据可能与他们的计算相关。因此,在开发的早期阶段,我不想为这些东西发明一个完整的规范模式,我宁愿只用 Objective-C 编写每一个,然后以某种方式将编译后的代码序列化到(CoreData)数据库中供以后召回和执行。

这有可能吗?我在想 GCD 块可能是一个很好的候选者,尽管我不知道有任何开箱即用的方法来序列化/反序列化它们。

感谢您的任何建议。

编辑:这是一个 iPhone 应用程序,所以不幸的是我不能使用 Python 函数酸洗之类的东西......它必须是直接的 Objective-C ......

4

1 回答 1

4

我认为不可能序列化块。

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

@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

现在你需要实现各种东西

@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. 然后您可以通过以下方式在不参考特定类型(X,Y,Z)的情况下复活促销对象

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

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

于 2010-07-24T17:35:51.513 回答