我的解决方案是使用自定义序列化。最后,所有数据都以属性列表的形式呈现。我所有应该序列化的自定义类都支持协议 PropertyListCoder(如 NSCoder):
@protocol PropertyListCoder
- (id)encodeToPropertyListObject;
- (id)initWithPropertyListObject:(id)object;
@end
例如,产品类的序列化:
@interface Product : NamedObject <NSCoding, PropertyListCoder> {
}
@property (nonatomic, readwrite) uint mId;
@property (nonatomic, retain) NSString *mDesc;
@property (nonatomic, retain) NSString *mIcon;
@property (nonatomic, retain) NSString *mCode;
@property (nonatomic, readwrite) uint mSort;
@property (nonatomic, retain) NSMutableArray *mArrOfText;
@property (nonatomic, readonly) NSMutableArray *mProperties;
@property (nonatomic, retain) NSString *mImage;
@property (nonatomic, readwrite) float mPrice;
@property (nonatomic, readwrite) float mDiscPrice;
@end
以下是协议的方法:
- (id)encodeToPropertyListObject {
id superPropList = [super encodeToPropertyListObject];
NSNumber* idNumber = [[NSNumber alloc] initWithInt:mId];
NSNumber* sortNumber = [[NSNumber alloc] initWithInt:mSort];
NSMutableArray* arrOfTextPropList = [[NSMutableArray alloc] init];
for (NSAttString* str in self.mArrOfText) {
[arrOfTextPropList addObject:[str encodeToPropertyListObject]];
}
NSMutableArray* propPropList = [[NSMutableArray alloc] init];
for (Property* prop in self.mProperties) {
[propPropList addObject:[prop encodeToPropertyListObject]];
}
NSNumber* priceNumber = [[NSNumber alloc] initWithInt:mPrice];
NSNumber* discPriceNumber = [[NSNumber alloc] initWithInt:mDiscPrice];
NSArray* res = [NSArray arrayWithObjects:superPropList, idNumber, [Utility notNilStringWithString:mDesc], [Utility notNilStringWithString:mIcon], [Utility notNilStringWithString:mCode], sortNumber, arrOfTextPropList, propPropList, [Utility notNilStringWithString:mImage], priceNumber, discPriceNumber, nil];
[idNumber release];
[sortNumber release];
[arrOfTextPropList release];
[propPropList release];
[priceNumber release];
[discPriceNumber release];
return res;
}
- (id)initWithPropertyListObject:(id)object {
NSArray* arr = (NSArray*)object;
self = [super initWithPropertyListObject:[arr objectAtIndex:0]];
if (self) {
mId = [[arr objectAtIndex:1] intValue];
mDesc = [[arr objectAtIndex:2] retain];
mIcon = [[arr objectAtIndex:3] retain];
mCode = [[arr objectAtIndex:4] retain];
mSort = [[arr objectAtIndex:5] intValue];
mArrOfText = [[NSMutableArray alloc] init];
mProperties = [[NSMutableArray alloc] init];
for (id subObj in (NSArray*)[arr objectAtIndex:6]) {
NSAttString* str = [[NSAttString alloc] initWithPropertyListObject:subObj];
[mArrOfText addObject:str];
[str release];
}
for (id subObj in (NSArray*)[arr objectAtIndex:7]) {
Property* prop = [[Property alloc] initWithPropertyListObject:subObj];
[mProperties addObject:prop];
[prop release];
}
mImage = [[arr objectAtIndex:8] retain];
mPrice = [[arr objectAtIndex:9] floatValue];
mDiscPrice = [[arr objectAtIndex:10] floatValue];
}
return self;
}
根对象可以是 NSDictionary 或 NSArray。然后对于读/写,我使用二进制格式的 NSPropertyListSerialization。而现在阅读字典需要 3.5 秒!