2009-10-29 45 views
6

最初我以为这会起作用,但现在我明白它不会因为artistCollection是“艺术家”对象的NSMutableArray。将对象的NSMutableArray保存/写入磁盘?

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

我的问题是什么是记录到磁盘上的我的“艺术家”对象的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]; 

编辑

非常感谢,只是最后一两件事我很好奇。如果“艺术家”包含额外的对象(应用程序)的NSMutableArray(softwareOwned)的实例变量,我将如何扩展编码来覆盖这个?我将NSCoding添加到“Applications”对象,然后在编码“Artist”之前对其进行编码,或者在“Artist”中指定此方法吗?

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

@interface Application : NSObject { 
    NSString *appName; 
    NSString *appVersion; 
} 

千恩万谢

加里

+0

为了回答您的编辑:只实现NSCoding为您的应用程序类并且在Artist的encodeWithCoder:和initWithCoder:中,添加行来处理可变数组的编码/解码。当被要求编码自身时,该数组然后会要求Application对象自己编码。 – 2009-10-29 20:22:51

+0

啊我明白了,完美,谢谢Ole。 – fuzzygoat 2009-10-29 20:44:58

回答

18

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]; 
9

看看的NSKeyedArchiver。简述:

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

您需要实现encodeWithCoder:你的艺术家类 - 看到Apple's docs

解除封存(见NSKeyedUnarchiver)就留给读者做练习:)