![](/img/trans.png)
[英]I need to use plist for data persistence. How can I store a value from a view controller into a plist and then display that value in a table view?
[英]How can I get n objects from pList file to display in my Table View?
我必须将plist文件中的所有对象(20个对象)显示给TableViewCell。 现在,我只想将plist文件中的11个对象显示给TableViewCell。
如果可以的话,我还希望从20个对象中随机抽取11个对象,并且不能重复。
请帮忙。
这是我的代码:
- (void)viewDidLoad {
[super viewDidLoad];
//get URL from plist file.
NSString* path = [[NSBundle mainBundle]pathForResource:@"playersList" ofType:@"plist"];
//Save plist file to an Array
self.listPlayer = [[NSArray alloc]initWithContentsOfFile:path];
}
_TableViewCell *方法:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString* cellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
// Configure the cell...
NSDictionary* eachPlayer = [self.listPlayer objectAtIndex:indexPath.row];
cell.textLabel.text = [eachPlayer objectForKey:@"Name"] ;
cell.detailTextLabel.text = [eachPlayer objectForKey:@"Position"];
return cell;
}
您可以像这样获得完整列表的随机子列表:
self.listPlayer = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSInteger numWantedPlayers = 11;
while (self.listPlayer.count > numWantedPlayers) {
NSUInteger indexToRemove = arc4random_uniform((uint32_t) all.count);
[self.listPlayer removeObjectAtIndex:indexToRemove];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.