2

我一直在尝试从 plist 文件中读取数据。这就是它的结构

|term|detail(string)|

我的属性:

@property (nonatomic, strong) NSArray *terms;
@property (nonatomic, strong) NSArray *termKeys;//this is just a array to keep track
@property (nonatomic, strong) NSString *detail;

这就是我访问详细信息的方式cellForRowAtIndexPath

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc]
                             initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];

    NSString *currentTermsName = [termKeys objectAtIndex :[indexPath row]];
                                  [[cell textLabel] setText:currentTermsName];
    cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;


    detail = [terms objectAtIndex:indexPath.row]; 

    NSLog(@" bombs %@",terms[@"Bomb Threats"]);
    return cell;

}

并鉴于 didload 我有

- (void)viewDidLoad
    {
        [super viewDidLoad];


        NSString *myfile = [[NSBundle mainBundle]
                            pathForResource:@"terms" ofType:@"plist"];
        terms = [[NSDictionary alloc] initWithContentsOfFile:myfile];
        termKeys = [terms allKeys];
    }

它访问值,但它为每个对象存储相同的值假设我在 plist 中有 5 条不同的记录,如果我打印详细信息,它会显示相同的记录 5 次。

设置详细信息后,我将其传递给 detialView

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if([segue.identifier isEqualToString:@"detailsegue"]){
        TermsDetailViewController *controller = (TermsDetailViewController *)segue.destinationViewController;
        controller.detailTerm = detail;
    }
}

最后:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self performSegueWithIdentifier:@"detailsegue" sender:self];
}

这是我的字典: http: //pastebin.com/bxAjJzHp

目标是将详细信息传递给 detailviewcontroller,就像 Master/detail 示例项目一样。

4

1 回答 1

1

您不能detail在方法中设置变量cellForRowAtIndexPath:,因为这样值会变为瞬态:它取决于用户如何滚动表格,而不是用户单击的显示按钮。

移动这条线

detail = [terms objectAtIndex:indexPath.row];

didSelectRowAtIndexPath:之前的电话performSegueWithIdentifier:来解决问题。现在detail设置为响应用户在调用前的点击prepareForSegue:,确保将正确的值与详细信息一起传递给视图控制器。

于 2013-03-04T21:01:07.897 回答