![](/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.