2010-04-17 1 views
6

В подклассе UITableViewController, есть некоторые методы, которые должны быть выполнены для того, чтобы загрузить данные и обрабатывать событие выбора строки:Может ли NSDictionary использоваться с TableView на iPhone?

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


} 

Как NSDictionary предполагается работать с TableView?

Каков самый простой способ сделать это?

ответ

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]]; 

значения теперь объект, выбранный в случае Tableview: didSelectRowAtIndexPath: или объект, который нужен для обработки клеток в Tableview: cellForRowAtIndexPath:

Если базовый NSDictionary изменяется, вам необходимо перезагрузить ([myTable reload] или тому подобное) UITableView.

+0

Ваше решение достаточно просто для меня. – bobo

+0

Простое решение, но это очень помогло мне! – stitz

3

Да. Вот как мы сделали это:

В нашем XML Parser мы имеем этот метод, который загружает XML в словарь под названием ДИКТ:

-(NSDictionary *)getNodeDictionary:(Node *)node { 
    if (node->level == 0) return xmlData; 
    else { 
     NSDictionary *dict = xmlData; 
     for(int i=0;i<node->level;i++) { 
      if ([[dict allKeys] containsObject:SUBNODE_KEY]) 
       dict = [[dict objectForKey:SUBNODE_KEY] objectAtIndex:*(node->branches+i)]; 
     } 
     return dict; 
    } 
} 

И этот метод

-(NSDictionary *)getDataForNode:(Node *)node { 
NSDictionary* dict = [[self getNodeDictionary:node] copy]; 
return dict; 

}

В классе RadioData имеется переменная экземпляра:

Node *rootNode; 

и куча методов

-(Node *)getSubNodesForNode:(Node *)node; 
-(Node *)getSubNodeForNode:(Node *)node atBranch:(NSInteger)branch; 
-(Node *)getParentNodeForNode:(Node *)node; 
-(NSInteger)getSubNodeCountForNode:(Node *)node; 
-(NSDictionary *)getDataForNode:(Node *)node; 

и недвижимость

@property (nonatomic) Node *rootNode; 

Наконец в ViewController, когда мы инициализации кадр мы используем:

radioData = data; 
curNode = data.rootNode; 

и внутри cellForRowAtIndexPath мы имеем:

Node* sub = [radioData getSubNodeForNode:curNode atBranch:indexPath.row]; 
NSDictionary* dets = [radioData getDataForNode:sub];  

и didSelectRowAtIndexPath:

Node* node = [radioData getSubNodeForNode:curNode atBranch:indexPath.row]; 
NSDictionary* data = [radioData getDataForNode:node]; 

Это, вероятно, больше, чем вы хотели, но это в общих чертах.

+0

Большое спасибо за ваше решение. Но для меня это сложно. – bobo

+0

Да ... его немного сложнее, но пример из довольно сложного приложения. К сожалению, у меня нет более простого примера. Это должно, однако, дать вам отправную точку. Возможно, использование массивов может быть проще. –