我有一个plist( images.plist ),内容如下

如您所见,每个项目都有一个数字键,范围是0-19。每个项目还具有两个字符串(fileName和fileInfo)。

我正在尝试将所有文​​件名加载到TableView中。这是我的尝试:

RosterMasterViewController.h

@interface RosterMasterViewController : UITableViewController

@property (nonatomic, strong) NSDictionary *roster;

@end

RosterMasterViewController.m
@implementation RosterMasterViewController

@synthesize roster = _roster;

...
// This is in my 'viewDidLoad'
NSString *file = [[NSBundle mainBundle] pathForResource:@"images" ofType:@"plist"];
self.roster = [NSDictionary dictionaryWithContentsOfFile:file];

这就是我试图将fileName加载到原型单元中的方式。

RosterMasterViewController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"imageNameCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // Configure the cell
    cell.textLabel.text = [[[self.roster allKeys] objectAtIndex:indexPath.row] objectForKey:@"fileName"];
   return cell;
}

注意
作为记录,我的CellIdentifier是正确的,如果将cell.textLabel.text设置为@"HELLO!",那么我将看到“HELLO!”。 NSDictionary中的每个项目。我在//Configure the cell部分遇到困难

不幸的是,这没有按我预期的那样工作。我遇到了麻烦,因为我的键都是数字键。

更新

尝试使用从以下答案中学到的知识,我有以下几点:
// Configure the cell
NSLog(@"Key: %@", [NSNumber numberWithInt:indexPath.row]);
NSDictionary *dict = [self.roster objectForKey:[NSNumber numberWithInt:indexPath.row]];
NSLog(@"Dictionary: %@", dict);
NSString *fileName = [dict objectForKey:@"fileName"];
NSLog(@"FileName: %@", fileName);

cell.textLabel.text = fileName;
return cell;

但这给了我这样的结果:
2012-02-03 11:24:24.295 Roster[31754:f803] Key: 7
2012-02-03 11:24:24.295 Roster[31754:f803] Dictionary: (null)
2012-02-03 11:24:24.296 Roster[31754:f803] FileName: (null)

如果我更改此行:
NSDictionary *dict = [self.roster objectForKey:[NSNumber numberWithInt:indexPath.row]];

至:
NSDictionary *dict = [self.roster objectForKey:@"5"];

然后,所有单元格的第6个元素都将具有正确的fileName。知道为什么[NSNumber numberWithInt:indexPath.row不起作用吗?

最佳答案

你可以这样做:

NSDictionary *dict = [self.roster objectForKey:indexPath.row];
NSString *fileName = [dict objectForKey:@"fileName"];

关于ios - 将plist加载到iOS TableView中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9130259/

10-09 08:04
查看更多