NSDictionary可以在iPhone上与TableView一起使用吗?

bob*_*obo 6 iphone objective-c nsdictionary uitableview

在UITableViewController子类中,为了加载数据和处理行选择事件,需要实现一些方法:

- (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


}
Run Code Online (Sandbox Code Playgroud)

NSDictionary如何与TableView一起使用?

完成这项工作的最简单方法是什么?

NSS*_*did 23

我不明白为什么你想要一个需要回答有序问题(行)的任务的字典(这是继承无序的),但我认为你已经从某个地方有一本字典而且不能改变它.如果是这种情况,则必须定义要显示键的顺序,从而隐式派生数组.一种方法是按字母顺序排列另一种方法如下:

// 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]];
Run Code Online (Sandbox Code Playgroud)

value现在是tableView:didSelectRowAtIndexPath:中选择的对象,或者是tableView中进行单元格处理所需的对象:cellForRowAtIndexPath:

如果底层NSDictionary发生更改,则必须重新加载([myTable reload]或类似)UITableView.