开发者

iphone - store id/value pairs in tableview

I have a php file which returns XML with id/value pairs. When I parse the XML I create an array of objects each having an id and a value. What I do now is add the value from the XML to the cell text. Also want to store the corresponding ID, so I can use it in the didSelectRowAtIndexPath method. I'm very new to the iPhone, so this might be obvious, sorry :)

Currently my cellForRowAtIndexPath method looks like this:

 - (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: c开发者_StackOverflow社区ategoryIndex] objectForKey: @"CategoryName"];
    cell.accessoryType = UITableViewCellSelectionStyleBlue;
    return cell;

}

The category object is defined like so:

category = [[NSMutableDictionary alloc] init];

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


There is no need to add the actual ID to the cell.

If you map the objects in your array to the UITableView 1:1 and your Table only has 1 group, you can just use the IndexPath's row as an index to the NSArray to retrieve the correct entry.

The first cell of your table will have row => 0 and the object corresponding to it in your array will also have the index of 0.

If you have several groups, then I assume your array will contain several sub-arrays to represent this. In that case, use the group portion of the IndexPath to jump to the right array and the row portion to jump to the right entry.

Alternative:

If you must for some reason include the ID in the actual cell, sublcass UITableViewCell and add a single NSNumber cellID to its interface.

Make sure to retain it in the property declaration and synthesize it.

Then, in your cellForRowAtIndexPath(), add

cell.cellID = [NSNumber numberWithInteger:YOURID];

This way you can later retrieve the cellID from the actual cell within didSelectRowAtIndexPath.


Use this in your didSelect method.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜