2010-04-17 9 views
6

En una subclase UITableViewController, hay algunos métodos que deben aplicarse a fin de cargar los datos y controlar el evento de selección de fila:¿Se puede usar NSDictionary con TableView en 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 


} 

cómo se supone que NSDictionary trabajar con TableView?

¿Cuál es la forma más sencilla de hacerlo?

Respuesta

23

No entiendo por qué quiere usar un diccionario (que heredado heredado) para una tarea que requiere respuestas a preguntas ordenadas (filas), pero supongo que ya tiene un diccionario de algún lado y no puede cambiar eso . Si ese es el caso, debe definir un orden en el que desea mostrar las claves, derivando así una matriz implícitamente. Una forma de hacer esto es alfabéticamente pedir otra es la siguiente:

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

valor es ahora el objeto seleccionado en el caso de tableView: didSelectRowAtIndexPath: o el objeto que necesita para su procesamiento celular en tableView: cellForRowAtIndexPath:

Si el NSDictionary subyacente cambia, tiene que volver a cargar (UIT-T) el UITableView ([myTable reload] o similar).

+0

Su solución es lo suficientemente simple para mí. – bobo

+0

¡Solución simple pero esto me ayudó mucho! – stitz

3

Sí. Aquí es cómo lo hemos hecho:

En nuestro analizador XML tenemos este método que carga el XML en un diccionario llamado dict:

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

Y este método

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

}

En la clase RadioData tenemos una variable de instancia:

Node *rootNode; 

y un montón de métodos

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

y una propiedad

@property (nonatomic) Node *rootNode; 

Finalmente en el ViewController cuando init del marco que utilizamos:

radioData = data; 
curNode = data.rootNode; 

y cellForRowAtIndexPath el interior tenemos:

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

y en didSelectRowAtIndexPath:

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

Esto es probablemente más de lo que quería pero que es el esquema general.

+0

Muchas gracias por su solución. Pero es complicado para mí. – bobo

+0

Sí ... es un poco complejo, pero el ejemplo es de una aplicación bastante compleja. Desafortunadamente, no tengo un ejemplo más simple a mano. Esto debería, sin embargo, darle un punto de partida. Quizás usar matrices sea más fácil. –

Cuestiones relacionadas