我认为不可能序列化块。
我会将数据封装到一个类中,并实现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 文档。