0

我正在尝试将选定表格视图行的单元格标题保存到 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 输出是:“来自项目列表:西班牙”

4

2 回答 2

2

在你的didSelectRowAtIndexPath你应该做以下

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

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

于 2012-11-20T12:47:28.467 回答
1

如果要保存所选国家/地区的名称,只需将其写为:

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

像这样检索它:

NSString *saved = (NSString *) [[NSUserDefaults standardUserDefaults] objectforKey:@"selectedCountry"];
于 2012-11-20T12:47:20.420 回答