質問

私はファイルが存在するかどうかを確認書く前に、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:私はマックのプログラミングに新たなんだと私は私が間違って何が起こっているのか私に語ったエラーメッセージを得ることはありませんので、試してみ他に何かわからない。

ファイルへのパスは次のとおりです。

  

/Users/andre/Documents/Contacts.plist

私は以前(同じ結果で)これを試してみましたが、私はあなただけのドキュメントフォルダに書き込むことができることを読みます:

  

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

これがなぜ起こるか誰もがアイデア、あるいは説明を持っていますか?

役に立ちましたか?

解決

方法:

あなたはstringByAppendingPathComponentでfilePathに設定されています。その方法は、自動解放オブジェクトを返します。

((自動的に)悪いアクセスエラーを引き起こす可能性があり、解放された後。自動解放オブジェクトが使用されています)

私は思う変更

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

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

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

他のヒント

まず、私はあなたがNSFileManagerオブジェクトをインスタンス化してはならないと思います。代わりに、あなたはこのように、デフォルトのファイルマネージャを使用します:

[[NSFileManager defaultManager] fileExistsAtPath: filePath];

これでプログラムがデバッガに破壊されている行すると、指定しただろうか?

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top