Error while checking if a file exists

cocoa, nsfilemanager, objective-c, plist

Solution

You are setting filePath with the stringByAppendingPathComponent: method. That method returns an autoreleased object. (Autoreleased object is used after it has been (automatically) released, which could cause the bad access error.)

I think changing

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

into

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

will solve your troubles.

Problem

I'm trying to write to a plist file using writeToFile, before I write I check whether the file exists. This is the code: ``` #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 ``` When the addContactAction is executed I don't get any error but the program halts and it brings me to the debugger. When I press continue in the debugger I get: ``` Program received signal: “EXC_BAD_ACCESS”. ``` But that's probably not important. PS: I'm new to mac programming and I don't know what else to try since I don't get an error message that tells me what's going wrong. The path to the file is: /Users/andre/Documents/Contacts.plist I earlier tried this(with the same result), but I read that you can only write to the documents folder: /Users/andre/Desktop/NN/NSTableView/build/Debug/NSTableView.app/Contents/Resources/Contacts.plist Does anyone have an idea or even an explanation why this happens?

Original source