Objective c 检查文件是否存在时出错
我正在尝试使用writeToFile写入plist文件,在写入之前,我会检查该文件是否存在 代码如下:Objective c 检查文件是否存在时出错,objective-c,cocoa,plist,nsfilemanager,Objective C,Cocoa,Plist,Nsfilemanager,我正在尝试使用writeToFile写入plist文件,在写入之前,我会检查该文件是否存在 代码如下: #import "WindowController.h" @implementation WindowController @synthesize contacts; NSString *filePath; NSFileManager *fileManager; - (IBAction)addContactAction:(id)sender { NSDictionary *d
#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被执行时,我没有得到任何错误,但是程序停止,它将我带到调试器。当我在调试器中按continue时,我得到:
Program received signal: “EXC_BAD_ACCESS”.
但这可能并不重要
PS:我是mac编程新手,我不知道还可以尝试什么,因为我没有收到错误消息来告诉我出了什么问题
文件的路径为:
/用户/andre/Documents/Contacts.plist
我之前尝试过这个方法(结果相同),但我读到您只能写入documents文件夹:
/Users/andre/Desktop/NN/NSTableView/build/Debug/NSTableView.app/Contents/Resources/Contacts.plist
有人知道或解释为什么会发生这种情况吗?首先,我认为不应该实例化NSFileManager对象。而是使用默认的文件管理器,如下所示:
[[NSFileManager defaultManager] fileExistsAtPath: filePath];
然后,您可以指定程序在哪一行进入调试器吗?您正在使用stringByAppendingPathComponent:方法设置filePath。该方法返回一个自动释放的对象。(自动释放的对象在(自动)释放后使用,这可能会导致错误的访问错误。) 我认为改变
[rootPath stringByAppendingPathComponent:@"Contacts.plist"];
进入
将解决您的问题。我在哪里可以看到它在哪一行断开?它只显示汇编代码。感谢fileManager的提示。删除了实例化,但没有更改任何内容。如果在Cocoa代码中崩溃,则只会看到程序集。调试器窗口左侧是堆栈帧列表;在你自己的代码中选择一个,你会看到你的源代码,相关的行用红色突出显示。哇,这确实解决了我的问题,谢谢!你能多告诉我一点问题是什么吗?我很确定这句话是从官方参考资料中抄来的。谢谢!我建议您看看本教程:。它有一句话:“在本教程中,您可以假设自动对象将在当前函数结束时消失。”(自动对象是自动释放对象)。您设置的字符串在awakeFromNib函数之后“消失”,因此filePath变量引用的内容不再存在,从而导致错误。保留它不会阻止它被自动删除,但会生成一个额外的副本,直到你告诉它才会发布。安德烈·霍夫曼(AndréHoffmann):苹果公司在ADC网站上有一个关于可可内存管理的隐藏良好但非常好的教程。谢谢我以为在Obj-C2.0中垃圾收集器会处理这个问题?或者这仍然是一种良好的做法?如果您使用垃圾收集,垃圾收集器会处理这些问题。它是可选的,默认为关闭。而且它在iPhone上不存在,因此如果您希望代码(特别是如果它是模型代码)在这两个位置都运行,您需要将其编写为retain counted或dual-mode(为retain counting和GC编写)。
[[rootPath stringByAppendingPathComponent:@"Contacts.plist"] retain];