将NSMutableArray对象保存/写入磁盘?

时间:2009-10-29 15:05:08

标签: objective-c cocoa

最初我认为这会起作用,但现在我明白它不会,因为artistCollection是“艺术家”对象的NSMutableArray。

@interface Artist : NSObject {
    NSString *firName;
    NSString *surName;
}

我的问题是,将“Artist”对象的NSMutableArray记录到磁盘的最佳方法是什么,以便我可以在下次运行应用程序时加载它们?

artistCollection = [[NSMutableArray alloc] init];

newArtist = [[Artist alloc] init];
[newArtist setFirName:objFirName];
[newArtist setSurName:objSurName];
[artistCollection addObject:newArtist];

NSLog(@"(*) - Save All");
[artistCollection writeToFile:@"/Users/Fgx/Desktop/stuff.txt" atomically:YES];

修改

非常感谢,这是我最好的一件事。如果“Artist”包含其他对象(Applications)的NSMutableArray(softwareOwned)的额外实例变量,我将如何扩展编码以涵盖此内容?我会将NSCoding添加到“Applications”对象,然后在编码“Artist”之前对其进行编码,还是有办法在“Artist”中指定它?

@interface Artist : NSObject {
    NSString *firName;
    NSString *surName;
    NSMutableArray *softwareOwned;
}

@interface Application : NSObject {
    NSString *appName;
    NSString *appVersion;
}
非常感谢

加里

2 个答案:

答案 0 :(得分:18)

Cocoa的集合类中的

writeToFile:atomically:仅适用于属性列表,即仅适用于包含NSString,NSNumber,其他集合等标准对象的集合。

要详细说明jdelStrother's answer,如果集合中包含的所有对象都可以自行存档,则可以使用NSKeyedArchiver对集合进行存档。要为您的自定义类实现此功能,请使其符合NSCoding协议:

@interface Artist : NSObject <NSCoding> {
    NSString *firName;
    NSString *surName;
}

@end


@implementation Artist

static NSString *FirstNameArchiveKey = @"firstName";
static NSString *LastNameArchiveKey = @"lastName";

- (id)initWithCoder:(NSCoder *)decoder {
    self = [super init];
    if (self != nil) {
        firName = [[decoder decodeObjectForKey:FirstNameArchiveKey] retain];
        surName = [[decoder decodeObjectForKey:LastNameArchiveKey] retain];
    }
    return self;
}   

- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:firName forKey:FirstNameArchiveKey];
    [encoder encodeObject:surName forKey:LastNameArchiveKey];
}

@end

有了这个,您可以对集合进行编码:

NSData* artistData = [NSKeyedArchiver archivedDataWithRootObject:artistCollection];
[artistData writeToFile: @"/Users/Fgx/Desktop/stuff" atomically:YES];

答案 1 :(得分:9)

看看NSKeyedArchiver。简而言之:

NSData* artistData = [NSKeyedArchiver archivedDataWithRootObject:artistCollection];
[artistData writeToFile: @"/Users/Fgx/Desktop/stuff" atomically:YES];

您需要在Artist类上实现encodeWithCoder:请参阅Apple's docs

Unarchiving(参见NSKeyedUnarchiver)留给读者练习:)