检查文件是否存在时出错

And*_*ann 5 cocoa objective-c plist nsfilemanager

我正在尝试使用writeToFile写入plist文件,在我写之前检查文件是否存在.

这是代码:

#import "WindowController.h"

@implementation WindowController

@synthesize contacts;

NSString *filePath;
NSFileManager *fileManager;

- (IBAction)addContactAction:(id)sender {

    NSDictionary *dict =[NSDictionary dictionaryWithObjectsAndKeys:
                         [txtFirstName stringValue], @"firstName",
                         [txtLastName stringValue], @"lastName",
                         [txtPhoneNumber stringValue], @"phoneNumber",
                         nil];

    [arrayContacts addObject:dict];

    [self updateFile];
}

- (void)awakeFromNib {
    NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    filePath    = [rootPath stringByAppendingPathComponent:@"Contacts.plist"];
    fileManager = [NSFileManager defaultManager];

    contacts = [[NSMutableArray alloc] init];

    if ([fileManager fileExistsAtPath:filePath]) {

        NSMutableArray *contactsFile = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
        for (id contact in contactsFile) {
            [arrayContacts addObject:contact];
        }
    }
}

- (void) updateFile {
    if ( ![fileManager fileExistsAtPath:filePath] || [fileManager isWritableFileAtPath:filePath]) {
        [[arrayContacts arrangedObjects] writeToFile:filePath atomically:YES];
    }
}

@end
Run Code Online (Sandbox Code Playgroud)

当执行addContactAction时,我没有收到任何错误,但程序停止,它将我带到调试器.当我在调试器中按继续时,我得到:

Program received signal:  “EXC_BAD_ACCESS”.
Run Code Online (Sandbox Code Playgroud)

但这可能并不重要.

PS:我是mac编程的新手,我不知道还有什么可以尝试,因为我没有收到错误消息告诉我出了什么问题.

该文件的路径是:

/Users/andre/Documents/Contacts.plist

我之前尝试过这个(结果相同),但我读到你只能写入文件夹:

/Users/andre/Desktop/NN/NSTableView/build/Debug/NSTableView.app/Contents/Resources/Contacts.plist

有没有人有想法甚至解释为什么会这样?

Oli*_*ler 9

首先,我认为您不应该实例化NSFileManager对象.而是使用默认文件管理器,如下所示:

[[NSFileManager defaultManager] fileExistsAtPath: filePath];
Run Code Online (Sandbox Code Playgroud)

那么,你能指定程序在哪一行进入调试器吗?


Pie*_*sma 2

您正在使用 stringByAppendingPathComponent: 方法设置 filePath。该方法返回一个自动释放的对象。(自动释放的对象在(自动)释放后使用,这可能会导致错误访问错误。)

我认为改变

[rootPath stringByAppendingPathComponent:@"Contacts.plist"];
Run Code Online (Sandbox Code Playgroud)

进入

[[rootPath stringByAppendingPathComponent:@"Contacts.plist"] retain];
Run Code Online (Sandbox Code Playgroud)

会解决你的烦恼。