代码之家  ›  专栏  ›  技术社区  ›  André Hoffmann

检查文件是否存在时出错

  •  5
  • André Hoffmann  · 技术社区  · 16 年前

    我正在尝试使用write to file写入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被执行时,我没有得到任何错误,但是程序停止,它将我带到调试器。当我在调试器中按Continue时,得到:

    Program received signal:  “EXC_BAD_ACCESS”.
    

    但这可能并不重要。

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

    文件路径为:

    /用户/andre/documents/contacts.plist

    我之前尝试过此操作(结果相同),但我看到您只能写入“文档”文件夹:

    /用户/andre/desktop/nn/nstableview/build/debug/nstableview.app/contents/resources/contacts.plist

    有人知道或者甚至解释了为什么会这样吗?

    2 回复  |  直到 16 年前
        1
  •  2
  •   Pieter Jongsma    16 年前

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

    我想改变

    [rootPath stringByAppendingPathComponent:@"Contacts.plist"];
    

    进入之内

    [[rootPath stringByAppendingPathComponent:@"Contacts.plist"] retain];
    

    会解决你的麻烦。

        2
  •  9
  •   Olivier 'Ölbaum' Scherler    16 年前

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

    [[NSFileManager defaultManager] fileExistsAtPath: filePath];
    

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