tags:

views:

33

answers:

3

I am trying to save and read back some application settings stored as NSStrings in an iPhone app and have been having some trouble.

The code to save looks like:

    NSMutableArray *array = [[NSMutableArray alloc] init];
   [array addObject:accountID];
    ...
   [array writeToFile:[self dataFilePath] atomically:YES];
   [array release];

And the code to read looks like (accountID is an NSString*):

    NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];         
    accountID = [array objectAtIndex:0];
    ...                     
    [array release];
    NSLog(@"Loading settings for: %@", accountID);

The read code throws an exception because after the array is released the accountID variable also appears to have been released (moving the NSLog call before releasing the array works fine). So I'm guessing that I'm creating a reference to the array instead of pulling out the actual string contained in the array. I tried several things to create new strings using the array contents but haven't had any luck.

+1  A: 

try [accountID retain] before you release the array

Sam Dufel
+2  A: 

When you release the array the reference to the accountID will also be released. You need to retain it.

accountID = [[array objectAtIndex:0] retain];

Then obviously at some point you need to release it.

willcodejavaforfood
+1  A: 

You guess is on the right lines although you have a reference to the 0th element of the array not the array. The array consists of pointers to NSString objects. The Strings will get get released when yhe array is released.

You need to retain the element you are using e/g/

NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];         
NSString* accountID = [[array objectAtIndex:0]retain];
...                     
[array release];
NSLog(@"Loading settings for: %@", accountID);
Mark