通常、ロードと保存を処理するカスタム クラスを 1 つ以上作成する方が簡単だと思います。これにより、配列を明示的に mutableArrays に変換できます。
MyThing.h
@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
MyThing.m
@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
これが完了すると、すべてのパッケージ化コードとアンパッケージ化コードをandsaveToFile
メソッドにカプセル化できます。このアプローチの主な利点は、メイン プログラムが非常に単純になり、データ構造の要素にプロパティとしてアクセスできるようになることです。
MyThing * thing = [[MyThing alloc] init];
[thing loadFromFile:@"..."];
...
thing.description = @"new description";
[thing.sections addObject:someObject];
[thing.items removeObjectAtIndex:4];
...
[thing saveToFile:@"..."];
[thing release];