开发者

Problem saving a plist

I was trying to use a plist to store an array with the below code:

NSString *name = firstName.text;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Names" ofType:@"plist"];

    NSMutableArray *namesArray = [[NSMutableArray alloc] initWithContentsOfFile:path];

    [namesArray addObject:name];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    [paths release];
    NSString *docDirPath = [documentsDirectory stringByAppendingPathComponent:@"Names.plist"];
    [namesArray writeToFile:docDirPath atomically:YES];

    namesArray = [[NSMutableArray alloc] initWithContentsOfFile:docDirPath];

This code seems to work. Using 开发者_如何学GoNSLog, I have found that after this code executes the plist contains what I want it to, however, my program crashes because it generates an EXC_BAD_ACCESS on a device, and on the simulator it just crashes without an explanation. Does anyone know why that might happen?


 NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES); //Auto-released array

NSString *documentsDirectory = [paths objectAtIndex:0];

[paths release]; //Oh noes!

You don't own the reference to paths, so don't release it. Remove [paths release] and I'll bet you're fine. You're crashing because the autorelease pool is releasing paths after you've already done it yourself.

Quoth the guide:

You only release or autorelease objects you own. You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” ... or if you send it a retain message.


Have you checked, at which place it is giving EXC_BAD_ACCESS error.

In your code there are two wrong things; those are.

The Plist file consists a dictionary not an array, Here in the code you are copying the file data to an array. and saving the array to the plist file.

Second one is you are releasing the "paths" array, with out completion of usage of it. you have to release that array at the end of the statements; like after updating the array to the file.

Regards,

Satya

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜