user1051935
user1051935

Reputation: 589

Unable to save NSMutableArray in NSUserDefaults

I am trying to save an NSMutableArray on device , but everytime I reload the application the data is erased.

I tried to use NSUserDefaults but the problem persists

here is the code I am using

-(void) addingData{

    [data addObject:theBarcodeString]; //data is the NSMutableArray

    [mainTableView reloadData]; //this is a UITableView where the data from the NSMutableArray is populated
    [self endText];
    history=[NSUserDefaults standardUserDefaults];
    [history        setObject:data          forKey:@"history"  ];
}

and here is where I load the data

- (void)viewDidLoad
{
    ...
    if (data == nil) {
        data = [[NSMutableArray alloc] init]; //onload it always goes to his line

    else {

        data=[[NSUserDefaults standardUserDefaults] objectForKey:@"history"  ];
    }
    ...
}

what am I doing wrong ?

Upvotes: 0

Views: 2355

Answers (2)

Alex Terente
Alex Terente

Reputation: 12036

synchronize Writes any modifications to the persistent domains to disk and updates all unmodified persistent domains to what is on disk.

  • (BOOL)synchronize

Return Value YES if the data was saved successfully to disk, otherwise NO.

So you have to add [history synchronize] to force write on the defaults

Edit: From Docs

Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.

So if you want to save changes immediately call [history synchronize].

Upvotes: 0

eric.mitchell
eric.mitchell

Reputation: 8855

You shouldn't be testing to see if data == nil. Instead, just do:

data = [[NSArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] 
    objectForKey:@"history"]];

Note that you will have to release that later.

If you want data to be a mutable array, you must use:

data = [[NSUserDefaults standardUserDefaults] mutableArrayValueForKey:@"history"];

If you try to performing mutating operations on data without using mutableArrayValueForKey, you will get a crash, because all objects returned from NSUserDefaults are immutable.

Upvotes: 3

Related Questions