5

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

誰かがこれが起こる理由についての考えや説明さえ持っていますか?

4

2 に答える 2

9

まず、NSFileManager オブジェクトをインスタンス化するべきではないと思います。代わりに、次のようにデフォルトのファイル マネージャーを使用します。

[[NSFileManager defaultManager] fileExistsAtPath: filePath];

それでは、プログラムがデバッガーに割り込む行を指定していただけますか?

于 2009-08-30T14:57:58.707 に答える
2

stringByAppendingPathComponent: メソッドで filePath を設定しています。そのメソッドは、自動解放されたオブジェクトを返します。(自動解放されたオブジェクトは、(自動的に) 解放された後に使用されるため、不正なアクセス エラーが発生する可能性があります。)

変わると思います

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

の中へ

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

あなたの悩みを解決します。

于 2009-08-30T15:07:00.377 に答える