如何将项目从didSelectRowAtIndexPath:保存到NSUserDefaults

时间:2012-11-20 12:42:49

标签: objective-c ios nsuserdefaults didselectrowatindexpath

我正在尝试将所选表格视图行的单元格标题保存到NSUserDefaults。我在 didSelectRowAtIndexPath:方法中有以下代码。此时这将保存整个listOfItems(NSMutableArray)。我希望能够保存和检索用户在表行中选择的listOfItems数组对象。

感谢您的帮助

这是在viewDidLoad中初始化的NSMutableArray:

listOfItems = [[NSMutableArray alloc] init];

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

didSelectRowAtIndexPath:方法

- (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]);
}

NSLog输出是:“来自项目列表:西班牙”

2 个答案:

答案 0 :(得分:2)

didSelectRowAtIndexPath中,您应该执行以下操作

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

然后以您需要的方式将其保存到用户默认值

答案 1 :(得分:1)

如果您想保存所选国家/地区的名称,请将其写为:

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

检索它:

NSString *saved = (NSString *) [[NSUserDefaults standardUserDefaults] objectforKey:@"selectedCountry"];