1
votes

I have a tab bar item which shows users favorites in a tableview. I have another tab bar item which shows a view and allows the user to add a favorite.

Update

this array of favourites gets read from NSUserDefaults in the viewDidLoadMethod of the class which creates and add a favorite.

NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
NSArray *prefs = [def arrayForKey:@"addedQuotes"];  
userAddedQuotes = [[NSMutableArray alloc] initWithArray:prefs];

then this code executes when the user actually adds a favorite

if([text1.text length] && [text2.text length])
{
    NSString *temp = [NSString stringWithFormat:@"%@^%@", 
    text1.text, text2.text];

    [userAdded addObject:temp];

    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];

    [myDefault setObject:userAdded forKey:@"addedFavorites"];

In the tableview class which loads this array from NSUserDefaults to display the values I use the following in the viewWillAppear method.

NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
NSArray *prefs = [def arrayForKey:@"addedFavorites"];   
favorites = [[NSMutableArray alloc] initWithArray:prefs];

At the moment if I add a favorite and then go to the show favorites tab view, it doesnt load the newly added items. only when I exit(press the home button) and start the application again.

How can I get the view to read from the userdefaults again when the tab bar item is selected and the view is shown?

Regards

1

1 Answers

2
votes

Have you tried calling synchronize on it?

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults synchronize];

Update for comments below - Your table should be using the data from the array that gets the NSUserDefaults loaded into it.

Your cellForRowAtIndexPath should look something like this (if you are re-using table cells, which you should be)

...

if (cell == nil) {

    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];     

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

}

// update cell
cell.textLabel.text = [myUserDefaultsArray objectAtIndex:indexPath.row];
NSLog(@"The table data should be %@", [myUserDefaultsArray objectAtIndex:indexPath.row]);

return cell;

You can quickly display the contents of the array to make sure it's getting updated when the view appears by doing this when the view appears (assuming you've already loaded your array)

int i = 0;

for (i; i<=[myUserDefaultsArray count] - 1; i++) {

    NSLog(@"data is %@ for row %d", [myUserDefaultsArray objectAtIndex:i], i);
}