0

I'm trying to save the cell title of a selected table view row to NSUserDefaults. I have the following code in the didSelectRowAtIndexPath: method. At the moment this saves the entire listOfItems (an NSMutableArray). I would like to be able to save and retrieve the listOfItems array object that the user selected in the table row.

thanks for any help

this is the NSMutableArray that is initialized in viewDidLoad:

listOfItems = [[NSMutableArray alloc] init];

[listOfItems addObject:@"Brazil"];
[listOfItems addObject:@"Italy"];
[listOfItems addObject:@"Spain"];
[listOfItems addObject:@"United Kingdom"];
[listOfItems addObject:@"United States"];

the didSelectRowAtIndexPath: method

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    // Customize archiver here
    [archiver encodeObject:listOfItems forKey:@"keyForYourArrayOfNSIndexPathObjects"];
    [archiver finishEncoding];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"keyForYourArrayOfNSIndexPathObjects"];


    NSKeyedUnarchiver *unarchiver;
    unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:
                  [[NSUserDefaults standardUserDefaults] objectForKey:@"keyForYourArrayOfNSIndexPathObjects"]];
    // Customize unarchiver here
    listOfItems2 = [unarchiver decodeObjectForKey:@"keyForYourArrayOfNSIndexPathObjects"];
    [unarchiver finishDecoding];

    NSLog(@"from the list of items: %@", listOfItems2[2]);
}

the NSLog output is: "from the list of items: Spain"

hanumanDev
  • 6,592
  • 11
  • 82
  • 146

2 Answers2

2

In your didSelectRowAtIndexPath you should do the following

int index = indexPath.row;
id obj = [listOfItems objectAtIndex:index];

Then save it to user defaults the way you need

Hemang
  • 26,840
  • 19
  • 119
  • 186
1

If you want to save the name of the selected country just write it like:

NSString *save = [listOfItems objectAtIndex:indexPath.row];
[[NSUserDefaults standardUserDefaults] setObject:save forKey:@"selectedCountry"];

Retrieve it like:

NSString *saved = (NSString *) [[NSUserDefaults standardUserDefaults] objectforKey:@"selectedCountry"];
Midhun MP
  • 103,496
  • 31
  • 153
  • 200