Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can NSDictionary be used with TableView on iPhone?

In a UITableViewController subclass, there are some methods that need to be implemented in order to load the data and handle the row selection event:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1; //there is only one section needed for my table view
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {              
    return [myList count]; //myList is a NSDictionary already populated in viewDidLoad method
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

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

    // indexPath.row returns an integer index, 
    // but myList uses keys that are not integer, 
    // I don't know how I can retrieve the value and assign it to the cell.textLabel.text


    return cell;
}


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

    // Handle row on select event, 
    // but indexPath.row only returns the index, 
    // not a key of the myList NSDictionary, 
    // this prevents me from knowing which row is selected


}

How is NSDictionary supposed to work with TableView?

What is the simplest way to get this done?

like image 983
bobo Avatar asked Apr 17 '10 04:04

bobo


1 Answers

I do not understand why you want to use a dictionary (which is inheritly unordered) for a task that requires answers to ordered questions (rows), but i take it that you have a dictionary already from somewhere and cannot change that. If that is the case, you have to define an order you want to display the keys in, thereby deriving an array implicitly. One way to do this is alphabetically order another one is the following:

// a) get an array of all the keys in your dictionary
NSArray* allKeys = [myList allKeys];
// b) optionally sort them with a sort descrriptor (not shown)
// c) get to the value at the row index
id value = [myList objectForKey:[allKeys objectAtIndex:indexPath.row]];

value is now the object selected in the case of tableView:didSelectRowAtIndexPath: or the object you need for your cell processing in tableView:cellForRowAtIndexPath:

If the underlying NSDictionary changes, you do have to reload ([myTable reload] or the like) the UITableView.

like image 125
NSSplendid Avatar answered Sep 22 '22 06:09

NSSplendid