2013-03-04 61 views
2

我一直在嘗試從plist文件讀取數據。這是它的結構如何閱讀plist文件,然後填充UItableView?

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

它訪問es值,但它爲每個對象存儲相同的一個讓我說我有5個不同的記錄plist,如果我打印的細節它顯示相同的記錄5次。

一旦細節設置,那麼我將它傳遞給detialView

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

和finaly:

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

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

的目標是將詳細信息傳遞給一個detailviewcontroller就像一個Master/detail示例項目。

回答

1

您不能在cellForRowAtIndexPath:方法中設置detail變量,因爲這樣該值就會變成瞬態的:它取決於用戶如何滾動表格,而不是用戶點擊哪個揭示按鈕。

移動此行

detail = [terms objectAtIndex:indexPath.row]; 

didSelectRowAtIndexPath:performSegueWithIdentifier:調用來解決這個問題之前。現在,detail被設置爲響應用戶在prepareForSegue:調用之前的點擊,確保將正確的值傳遞給具有詳細信息數據的視圖控制器。

+0

謝謝你的解決方案,你的解決方案拋出一個異常:-' [__ NSArrayM objectForKey:]:無法識別的選擇器發送到實例0xaa55a40'可能是什麼問題 – meda 2013-03-04 21:06:25

+0

@meda我從你的代碼複製了一行,所以我懷疑這是另一回事。 'objectForKey:'的調用是針對'terms',它是'NSDictionary',而不是'NSArray'。您確定崩潰來自修改後的代碼,而不是來自新視圖控制器的代碼,因爲該異常而沒有機會打開該代碼? – dasblinkenlight 2013-03-04 21:12:25

+0

這是我的第一個應用程序,所以我可能有幾個錯誤,你有什麼建議 – meda 2013-03-04 21:21:57