iphone - 如何将 NSMutableArray(包含其他数组)保存到文件

标签 iphone objective-c cocoa-touch nscoder

以前有人问过这个问题,人们已经就如何做到这一点给出了很好的说明,例如here .

但是,我想知道如果我只是想将一个 NSMutableArray(包含另一个 NSMutableArray 的各种实例)保存到一个文件中,是否真的需要使用 NSCoder?我试过了,但只收到一条错误消息:

    -(void)saveLibraryDat {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"myLibrary.dat"];
    NSError *error;

    [myLibrary writeToFile:filePath atomically:YES];

    if (error) {
        NSLog(@"There was an error saving myLibrary.dat: %@", error);
    }

}

我的错误信息:

2011-05-13 22:00:47.840 MoleNotes[15437:207] There was an error saving myLibrary.dat: (
    1,
    2
)

所以我想我必须使用 NSCoder,对吧?如果是这样,我想知道如何去做。人们已经解释了如何用一个类来做到这一点,但在我的例子中,我有一个 NSMutableArray (myLibrary),它包含一个类的各种实例。我是否必须在此类和 NSMutableArray 中实现 NSCoder?

我这样分配我的图书馆:

    myLibrary = [[NSMutableArray alloc] init];

然后像这样添加一个名为 NoteBook.m 的类的实例:

    NoteBook *newNoteBook = [[NoteBook alloc] init];
       newNoteBook.titleName = @"Notes"; // etc.

[myLibrary addObject:newNoteBook];

那么我到底应该把 NSCoder 命令放在哪里呢?只进入我的 NoteBook.m 类?这会自动处理 myLibrary 吗?

感谢您的任何建议。


编辑:

所以我更新了我的代码,但我想最大的问题是我的 NSMutableArray myLibrary 包含我设置的自定义类(称为笔记本)的几个实例。我已经为这个类(及其所有变量)设置了 NSCoding,以便我可以保存和加载它。

现在,如果我在应用程序中创建 NSMutableArray(即,当应用程序第一次启动时,不存在文件),而不是从磁盘加载它,我的应用程序将完全正常工作:

    -(void) setupLibrary {

    myLibrary = [[NSMutableArray alloc] init];

    NoteBook *newNoteBook = [[NoteBook alloc] init];

    newNoteBook.titleName = @"Notes"; 
/...

如果我从磁盘加载它,它也能正常工作:

-(void)loadLibraryDat {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"myLibrary.dat"];

    myLibrary = [[NSMutableArray alloc] init];  
    myLibrary = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

    if (!myLibrary) {
        // if it couldn't be loaded from disk create a new one
        NSLog(@"myLibrary.dat empty... set up new one");


        [self setupLibrary];
        } else { NSLog(@"Loading myLibrary.dat successful."); }

    }

如果我在加载后记录我的库中包含的所有内容,一切仍然很好。例如。以下工作完全正常:

    NSLog(@"%@", [[self.myLibrary objectAtIndex:0] titleName]); 

然而,最大的问题是,如果任何其他方法试图访问 myLibrary。例如,如果我从另一个方法调用完全相同的日志命令,应用程序将崩溃并且我收到此错误消息:

    [NSCFString objectAtIndex:]: unrecognized selector sent to instance 0x4b38510
2011-05-14 14:09:10.490 Notes[17091:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString objectAtIndex:]: unrecognized selector sent to instance 0x4b38510'

这听起来好像 myLibrary 已被释放,但我不明白为什么。这怎么可能发生?我觉得我在我的 NSCoding 设置中做错了......因为如果我只是在代码中创建 myLibrary,一切都会很好地工作。只有当我从磁盘加载它时,应用程序才会崩溃。


这是类设置:

  #import <Foundation/Foundation.h>

@interface NoteBook : NSObject <NSCoding> {

    NSString *titleName;

    NSString *fileName;
    NSMutableArray *tabTitles;
    NSMutableArray *tabColours;
    NSMutableArray *tabReference;   

}

@property (nonatomic, retain) NSString *titleName;

@property (nonatomic, retain) NSString *fileName;
@property (nonatomic, retain) NSMutableArray *tabTitles;
@property (nonatomic, retain) NSMutableArray *tabColours;
@property (nonatomic, retain) NSMutableArray *tabReference;

-(id)initWithCoder:(NSCoder *)aDecoder;
-(void)encodeWithCoder:(NSCoder *)aCoder;


@end


//
//  NoteBook.m

#import "NoteBook.h"


@implementation NoteBook

@synthesize titleName, fileName, tabTitles, tabColours, tabReference;

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (self) {
        self.titleName = [aDecoder decodeObjectForKey:@"titleName"];
        self.fileName = [aDecoder decodeObjectForKey:@"fileName"];
        self.tabTitles = [aDecoder decodeObjectForKey:@"tabTitles"];
        self.tabColours = [aDecoder decodeObjectForKey:@"tabColours"];
        self.tabReference = [aDecoder decodeObjectForKey:@"tabReference"];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:titleName forKey:@"titleName"];
    [aCoder encodeObject:fileName forKey:@"fileName"];
    [aCoder encodeObject:tabTitles forKey:@"tabTitles"];
    [aCoder encodeObject:tabColours forKey:@"tabColours"];
    [aCoder encodeObject:tabReference forKey:@"tabReference"];
}

@end

编辑:

我想我已经解决了......我忘记了一点“ self ”......这把它搞砸了并释放了我的图书馆:

    self.myLibrary = [NSKeyedUnarchiver
                   unarchiveObjectWithFile:filePath];

if (self.myLibrary == nil) {
    NSLog(@"myLibrary.dat empty... set up new one");
    [self setupLibrary];
} else { NSLog(@"Loading myLibrary.dat successful."); }

最佳答案

您的代码被破坏了。 “错误”变量未初始化且从未设置,因此当您检查它时,您只会看到随机的垃圾数据。如果想知道写入是否成功,查看writeToFile:atomically:的返回值。如果写入成功则为 YES,否则为 NO

但是,NSArray 的writeTo… 方法用于创建plist。如果非属性列表对象在您的数组中,则该方法不合适,而归档器正是您想要的。只需执行类似 [[NSKeyedArchiver archivedDataWithRootObject:myLibrary] writeToFile:writeToFile:filePath atomically:YES] 的操作即可。

为了使您的对象正确地符合 NSCoding,只需让它们实现 initWithCoder:encodeWithCoder:,并在这些方法中使用 NSCoder's storage methods存储对象的实例变量(以及将它们取回的检索方法)。

关于iphone - 如何将 NSMutableArray(包含其他数组)保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6000679/

相关文章:

objective-c - 如何避免不同的类别扩展定义相同的方法

ios - 获取UITableView的最小高度

iphone - 关于在 iPhone 上加速 OpenGL ES 1.1 的建议

ios - 我在创建一个单例吗?

objective-c - 制作线条动画的最简单方法是什么?

ios - 如何在 iOS 上使用代码获取屏幕尺寸?

objective-c - https 上的 GET 错误??无法设置 NSLocalizedRecoverySuggestion

iphone - 应用程序引用 Payload 中的非公共(public)选择器

iphone - ios:字符串到日期的转换

iphone - 在 accessoryView 上设置 alpha 透明度