2011-11-27 63 views
1

我有以下的代碼,以使一個表從字符串變成詞典:的UITableView:在詳細視圖中使用對象從字典作爲標題

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    testArray = [[NSArray alloc] init]; 
    NSString *testString = @"Sam|26,Hannah|22,Adam|30,Carlie|32"; 
    testArray = [testString componentsSeparatedByString:@","]; 

    dict = [NSMutableDictionary dictionary]; 
    for (NSString *s in testArray) { 
     testArray2 = [s componentsSeparatedByString:@"|"]; 
     [dict setObject:[testArray2 objectAtIndex:1] forKey:[testArray2 objectAtIndex:0]]; 
    } 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; 
    } 

    // Configure the cell. 
    if (testArray.count >indexPath.row) { 
     cell.textLabel.text = [[dict allKeys] objectAtIndex:[indexPath row]]; 
     cell.detailTextLabel.text = [dict objectForKey:cell.textLabel.text]; 
    } 

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 

    return cell; 
} 

我想是對於選擇的行標題設置作爲我詳細視圖上的標題。

我試着用:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

    self.detailController.title = [[dict allKeys] objectAtIndex:[indexPath row]]; 

    [self.navigationController pushViewController:self.detailController animated:YES]; 
} 

但我得到一個 「EXC_BAD_ACCESS」 錯誤。

,如果我使用@「1」作爲標題它工作正常,這只是一些與我的字典裏調用這是錯誤的,我認爲。

+0

我沒有在你的代碼看到你在哪裏申報或創建detailController ...是self.detailController在'didSelectRowAtIndexPath'方法有效(而不是無效)?它有一個'title'屬性嗎? –

+0

是的,一切都是有效的。如果我使用@「1」作爲標題,一切正常,這只是我的字典調用錯誤。 –

回答

0

使dict成爲一個保留的字典,而不是一個自動發佈的字典。

I.E.在viewDidLoad方法

dict = [[NSMutableDictionary alloc] initWithCapacity: [testArray count]]; 

:也許聲明它是這樣的。請務必將其釋放時viewDidUnload被調用。

此外,確保按鍵的數量在你的dict調用之前:

self.detailController.title = [[dict allKeys] objectAtIndex:[indexPath row]]; 

所以,我會做:

if(dict && ([[dict allKeys] count] > [indexPath row]) 
{ 
    self.detailController.title = 
     [[dict allKeys] objectAtIndex:[indexPath row]]; 
} else { 
    self.detailController.title = @"Here's a problem"; 
} 
0

你實現這些UITableView委託方法?所有這些都是需要的。你也可以發佈更詳細的StackTrace。

- (NSInteger)tableView:(UITableView *)tableView 
numberOfRowsInSection:(NSInteger)section 
{ 
    return [resultSet count]; 
} 


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 


- (CGFloat)tableView:(UITableView *)tableView 
heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return 280.0; 
} 
+0

是的,一切都是有效的。如果我使用@「1」作爲標題,一切正常,這只是我的字典調用錯誤。 –

相關問題