1

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.

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

try [accountID retain] before you release the array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.