1

我正在做一个有各种自定义对象的项目。这些自定义对象(其中一些与嵌套的可变数组一起使用)需要保存到一个文件/或多个文件中。这样做的最佳方法是什么?我应该创建一个加载和保存文件管理器还是让每个对象处理它会更好?

感谢您的时间。

——史蒂文

4

3 回答 3

1

为您的班级实施NSCoding协议:

NSString * const kMyArray = @"myString";
NSString * const kMyBool = @"myBool";

- (void)encodeWithCoder:(NSCoder *)coder
{
    [coder encodeObject:_myArray forKey:kMyArray];
    [coder encodeBool:_myBool forKey:kMyBool];
    //...
}

- (id)initWithCoder:(NSCoder *)coder
{
    self = [super init];
    if (self) {
        _myArray = [coder decodeObjectForKey:kMyArray];
        _myBool = [coder decodeBoolForKey:kMyBool];
        //...
    }
    return self;
}

它允许您保存和加载数据NSKeyedArchiver

//saving collection of Class<NSCoding> objects
NSString *documentsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
BOOL success = [NSKeyedArchiver archiveRootObject:_collection toFile:path];

//loading
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
if (data) _collection = [NSKeyedUnarchiver unarchiveObjectWithData:data];
于 2012-10-26T08:30:48.213 回答
0

如果你想编码和解码对象,你可以看看 NSCoding。这是一种直截了当的方法。

查看文档:https ://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Protocols/NSCoding_Protocol/Reference/Reference.html (编辑正确链接)

更新存储对象损坏的 iOS 版本时,我遇到了问题。这是围绕从 iOS 4.1 到 iOS 4.2 的过渡。

我停止使用 NSCoder 并切换到创建自定义文件格式,它具有底层 JSON 文件。现在我对文件版本控制有了更多的控制,并且可以轻松地进行修复,因为这完全是关于解释您自己的数据文件。

于 2012-10-26T08:30:59.070 回答
0

您可以在您的应用程序包中手动创建一个 plist 文件(假设Config.plist是 plist 的名称),并将其复制到 Document 目录后,您可以通过编程方式对其进行修改。

所以看看这里如何将你的文件复制到文档目录中:首先定义两个宏:

#define DOCUMENT_DIR        [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]
#define PLIST_SETTINGS      [DOCUMENT_DIR stringByAppendingPathComponent:@"Config.plist"]

之后 -

 NSString *configPath = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"];
[self copyIfNeededFrom:configPath To:PLIST_SETTINGS];
 NSMutableArray* mArrObjects = [NSMutableArray alloc] initWithObjects:obj1,obj2,obj3, nil];
[mArrObjects writeToFile:PLIST_SETTINGS atomically:YES];
[mArrObjects release];

现在给出copyIfNeededFrom: 的定义:

- (BOOL)copyIfNeededFrom:(NSString *)sourcePath To:(NSString *)destinationPath
{
NSError *error = noErr;
if(![[NSFileManager defaultManager] fileExistsAtPath:destinationPath])
{
    [[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:destinationPath error:&error];
}
if(noErr)
    return YES;
else
    return NO;
}

希望对你有效。干杯!!!

于 2012-10-26T08:43:11.890 回答