views:

1394

answers:

2

Hi,

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?

+1  A: 

First, I think you shouldn't instantiate an NSFileManager object. Instead you use the default file manager, like this:

[[NSFileManager defaultManager] fileExistsAtPath: filePath];

Then, could you specify at which line the program is breaking into the debugger?

Ölbaum
Where can I see at which line it breaks? It only shows assembly code. Thanks for the hint with the fileManager..removed the instantiation, but didn't change a thing.
André Hoffmann
If you crash inside Cocoa code, you'll see only assembly. On the left side of the Debugger window is a list of stack frames; pick one that's in your own code, and you'll see your source code, with the relevant line highlighted in red.
Peter Hosey
Thank you Peter.
André Hoffmann
+1  A: 

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.

Jongsma
Wow, that indeed fixed my problem, thanks! Could you tell me a bit more about what the problem was? I'm pretty sure I copied this line from the official reference. Thanks a lot!
André Hoffmann
I recommend you take a look at this tutorial: http://cocoadevcentral.com/d/learn_objectivec/. It has a line saying "For this tutorial, you can assume that an automatic object will go away at the end of the current function." (Automatic object being autoreleased object). The string you set 'disappears' after the awakeFromNib function, so the filePath variable references something that doesn't exist anymore, causing errors. Retaining it will not stop it from being autoreleased, but will make an extra copy which isn't released until you tell it to. (Which you should probably do in -dealloc.)
Jongsma
André Hoffmann: Apple has a well-hidden but very good tutorial on Cocoa memory management on the ADC website. http://developer.apple.com/mac/library/documentation/General/Conceptual/DevPedia-CocoaCore/MemoryManagement.html
Peter Hosey
Thanks! I thought in Obj-C 2.0 the garbage collector takes care of that? Or is it still good practice?
André Hoffmann
Yes, you are correct. I program for the iPhone :)
Jongsma
The garbage collector does take care of that *if* you use garbage collection. It's optional, and off by default. And it doesn't exist on the iPhone, so if you want the code (especially if it's model code) to run in both places, you need to write it as either retain-counted or dual-mode (written for both retain-counting and GC).
Peter Hosey