2011-06-16 32 views
0

我有一個php文件,它返回帶有id /值對的XML。 當我解析XML時,我創建了一個對象數組,每個對象都有一個id和一個值。 我現在所做的是將XML中的值添加到單元格文本中。也想存儲相應的ID,所以我可以在didSelectRowAtIndexPath方法中使用它。 我很新的iPhone,所以這可能是顯而易見的,不好意思:)iphone - 在tableview中存儲id /值對

目前我的cellForRowAtIndexPath方法是這樣的:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *MyIdentifier = @"MyIdentifier"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; 
    if(cell == nil) 
    { 
     cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease]; 
    } 
    int categoryIndex = [indexPath indexAtPosition: [indexPath length] -1]; 
    cell.textLabel.text = [[categories objectAtIndex: categoryIndex] objectForKey: @"CategoryName"]; 
    cell.accessoryType = UITableViewCellSelectionStyleBlue; 
    return cell; 

} 

類別對象的定義,像這樣:

category = [[NSMutableDictionary alloc] init]; 

[category setObject:currentID forKey:@"CategoryId"]; 
     [category setObject:currentName forKey:@"CategoryName"]; 

回答

3

沒有必要將實際的ID添加到單元格中。

如果您將數組中的對象映射到UITableView 1:1並且您的表只有1個組,則可以使用IndexPath的行作爲NSArray的索引來檢索正確的條目。

表中的第一個單元格將有row => 0,並且陣列中與它對應的對象也將具有0的索引。

如果你有幾個組,那麼我假設你的數組將包含幾個子數組來表示這個。在這種情況下,使用IndexPath的組部分跳轉到正確的數組,並將行部分跳轉到正確的條目。

備選:

如果必須出於某種原因包括在實際的細胞,sublcass UITableViewCell的ID,並添加一個單一的NSNumber cellID到它的接口。

確保將其保留在屬性聲明中併合成它。

然後,在你的cellForRowAtIndexPath(),添加

cell.cellID = [NSNumber numberWithInteger:YOURID]; 

這樣你可以在以後內didSelectRowAtIndexPath檢索實際電池的cellID

+0

謝謝!我實際上會選擇繼承。 – 2011-06-16 23:51:08

1

在你的didSelect方法中使用它。

int categoryIndex = [indexPath indexAtPosition: [indexPath length] -1]; 
NSString *id = [[categories objectAtIndex:categoryIndex] objectForKey: @"CategoryId"];