要创建这种结构非常简单,您可以创建一个字典,其中包含键“卡片”的数组值。下面的例子..
NSMutableDictionary *cards = [NSMutableDictionary dictionary];
NSMutableArray *cardArray = [NSMutableArray array];
NSMutableDictionary *item = [NSMutableDictionary dictionary];
[item setValue:@"Card Name" forKey:@"Name"];
[item setValue:@"Card Number" forKey:@"Number"];
[item setValue:@"Card Type" forKey:@"Type"];
[cardArray addObject:item];
[cards setValue:cardArray forKey:@"Cards"];
[[NSUserDefaults standardUserDefaults] setValue:cards forKey:@"user_cards"];
[[NSUserDefaults standardUserDefaults] synchronize];
为了检索你的卡片,你会做类似的事情。假设 self.cards 是一个 NSMutableArray ivar 。
NSMutableDictionary *stored = [[NSUserDefaults standardUserDefaults] valueForKey:@"user_cards"];
self.cards = [stored valueForKey:@"Cards"];
您的 tableview 应该使用cards
ivar 来填充您的数据,如下所示。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
......
//Now we populate each row of the cell with each `card` Name.
cell.textLabel.text = [[self.cards objectAtIndex:[indexPath row]] valueForKey:@"Name"];
.....
}
要将任何新添加的卡片重新保存到存储的字典中,您可以执行以下操作..
NSMutableDictionary *newCard = [NSMutableDictionary dictionary];
[newCard setValue:@"Card Name" forKey:@"Name"];
[newCard setValue:@"Card Number" forKey:@"Number"];
[newCard setValue:@"Card Type" forKey:@"Type"];
[self.cards addObject:newCard];
[[NSUserDefaults standardUserDefaults] valueForKey:@"user_cards"] setValue:self.cards forKey:@"Cards"];
[[NSUserDefaults standardUserDefaults] synchronize];
如果这对您的问题有所帮助,请接受它作为答案。