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