将plist加载到iOS TableView中

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

images.plist

正如你所看到的,每个项目都有一个从0到19的数字键。 每个项目也有两个string(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]; 

这就是我想如何加载文件名到原型单元格。

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; } 

注意对于logging,我的CellIdentifier是正确的,如果我把cell.textLabel.text设置为@"HELLO!" ,那么我会看到“你好!” 为NSDictionary中的每个项目。 我有困难//Configure the cell部分

不幸的是,这并不像我预期的那样工作。 我有困难,因为我的钥匙都是数字我想。

UPDATE

尝试使用我从下面的答案中学到的东西,我有这样的:

 // 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"]; 

然后所有的单元格将有第六个元素的正确的文件名。 任何想法为什么[NSNumber numberWithInt:indexPath.row不工作?

你可以这样做:

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

正如Oscar所指出的,self.roster是一个NSDictionary,每个数字键都有一个字典。

你必须先检索数字键的NSDictionary *fileDictionary = [self.roster objectForKey:indexPath.row];NSDictionary *fileDictionary = [self.roster objectForKey:indexPath.row];

之后,你必须从这个最后的字典中提取你的文件名,所以你必须为@“fileName”键请求string。

  NSString *fileName = [fileDictionary objectForKey:@"fileName"]; cell.textLabel.text = fileName; return cell; 

不知道如果你已经解决了这个问题,但下面是我如何解决这个问题。

 NSDictionary *dict = [self.allItem objectForKey:[NSString stringWithFormat:@"%d",indexPath.row]]; 

我认为原因是[NSNumber numberWithInt:indexPath.row]返回数字/ [NSNumber numberWithInt:indexPath.row]数值。 但objectForKey:期待收到一个string值。

希望这个帮助。