我正在尝试使用 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
执行 addContactAction 时,我没有收到任何错误,但程序停止并将我带到调试器。当我在调试器中按继续时,我得到:
Program received signal: “EXC_BAD_ACCESS”.
但这可能并不重要。
PS:我是 mac 编程的新手,我不知道还能尝试什么,因为我没有收到告诉我出了什么问题的错误消息。
该文件的路径是:
/Users/andre/Documents/Contacts.plist
我之前尝试过这个(结果相同),但我读到你只能写入文档文件夹:
/Users/andre/Desktop/NN/NSTableView/build/Debug/NSTableView.app/Contents/Resources/Contacts.plist
有没有人知道为什么会发生这种情况?