开发者

Populating UITableView with Dictionary Data

My Situation:

I have an NSDictionary object. Keyed by NSNumber. Values are custom objects.

I want to put di开发者_JAVA技巧ctionary values into a UITableView. As far as I can tell, UITableView requires that its source collection be indexed so when cellForRowAtIndexPath is called, you can use the indexPath to look up the value.

Problem is that when didSelectRowAtIndexPath is called, I want to look up the object from the dictionary, but I don't have the key. All I have is the indexPath.row.

My solution: I create an array of keys. I use the index of the array to get the key, and then use the key to get the object out of the dictionary.

My problem: This seems kind of sloppy especially since this is a routine task (populating the UITableView and then responding when someone touches a cell). Is this the way it's designed to work or is there a better way?


The problem is that dictionaries don't have an order, while a table view does. The answers to this question should give you some ideas for alternative ways of handling this.


As mentioned in another answer, an NSDictionary's keys are not ordered, therefore you are not guaranteed to get the rows in a particular order. That said, it is quite easy to use a dictionary for use with a UITableView.

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //  tableview cell setup

    NSArray* keys = [self.data allKeys];

    cell.textLabel.text = [self.data objectForKey:[keys objectAtIndex:indexPath.row]];

    return cell;
}

If you need the list to be ordered according to how you entered them into the NSDictionary, Matt Gallagher from Cocoa With Love offers an elegant solution with his take on OrderedDictionary. You can read about it here.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜