objective-c – 将NSMutableArray对象保存/写入磁盘?

前端之家收集整理的这篇文章主要介绍了objective-c – 将NSMutableArray对象保存/写入磁盘?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
最初我认为这会起作用,但现在我明白它不会因为artistCollection是“Artist”对象的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;
}

非常感谢

加里

解决方法

writeToFile:atomically:在Cocoa的集合类中仅适用于属性列表,即仅适用于包含标准对象(如NSString,NSNumber,其他集合等)的集合.

要详细说明jdelStrother’s answer,如果集合包含的所有对象都可以自行存档,则可以使用NSKeyedArchiver对集合进行存档.要为您的@R_301_451@类实现此功能,请使其符合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];
原文链接:https://www.f2er.com/c/117467.html

猜你在找的C&C++相关文章