我通常发现创建一个或多个自定义类来处理加载和保存更容易。这使您可以将数组显式转换为 mutableArrays:
我的东西
@interface MyThing : NSObject
{
NSString * description;
NSMutableArray * sections;
NSMutableArray * items;
}
@property (copy) NSString * description;
@property (readonly) NSMutableArray * sections;
@property (readonly) NSMutableArray * items;
- (void)loadFromFile:(NSString *)path;
- (void)saveToFile:(NSString *)path;
@end
我的东西
@implementation MyThing
@synthesize description;
@synthesize sections
@synthesize items;
- (id)init {
if ((self = [super init]) == nil) { return nil; }
sections = [[NSMutableArray alloc] initWithCapacity:0];
items = [[NSMutableArray alloc] initWithCapacity:0];
return self;
}
- (void)dealloc {
[items release];
[sections release];
}
- (void)loadFromFile:(NSString *)path {
NSDictionary * dict = [NSDictionary dictionaryWithContentsOfFile:path];
[self setDescription:[dict objectForKey:@"description"]];
[sections removeAllObjects];
[sections addObjectsFromArray:[dict objectForKey:@"sections"]];
[items removeAllObjects];
[items addObjectsFromArray:[dict objectForKey:@"items"]];
}
- (void)saveToFile:(NSString *)path {
NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:
description, @"description",
sections, @"sections",
items, @"items",
nil];
[dict writeToFile:path atomically:YES];
}
@end;
完成后,您可以将所有打包和解包代码封装在loadFromFile
和saveToFile
方法中。这种方法的主要好处是您的主程序变得更加简单,并且它允许您将数据结构的元素作为属性访问:
MyThing * thing = [[MyThing alloc] init];
[thing loadFromFile:@"..."];
...
thing.description = @"new description";
[thing.sections addObject:someObject];
[thing.items removeObjectAtIndex:4];
...
[thing saveToFile:@"..."];
[thing release];