2010-08-28 14 views
2

Je tente d'utiliser le code ci-dessous dans une fonction pour renvoyer un tableau d'objets du dictionnaire. Malheureusement, après le retour à la fonction suivante dans la pile, toutes les lignes du tableau mutable sont devenues 'hors de portée'. D'après ce que je comprends, le tableau devrait conserver l'objet ligne (dictionnaire) automatiquement, même après le retour, où le pointeur de ligne est hors de portée, les objets de ligne devraient toujours avoir un nombre de retenue de 1. Que fais-je tort ici? Comment puis-je construire ce tableau de telle sorte que les objets qu'il contient ne soient pas libérés?Les objets NSArray ne sont plus visibles après le renvoi du pointeur

for (int i = 1; i < nRows; i++) 
{ 
    NSMutableDictionary* row = [[[NSMutableDictionary alloc] initWithCapacity:nColumns] ]; 
    for(int j = 0; j < nColumns; j++) 
    { 
    NSString* key = [[NSString stringWithUTF8String:azResult[j]] ]; 
    NSString* value = [[NSString stringWithUTF8String:azResult[(i*nColumns)+j]] ]; 

    [row setValue:value forKey:key]; 
    } 
    [dataTable addObject:row]; 
} 

return dataTable; 
+0

Veuillez reformater ce code (pour la facilité de lecture) et nous montrer comment vous créez et maintenez le dataTable. –

+0

Pourquoi voulez-vous dire par «hors de portée»? Pourquoi utilisez-vous NSMutableDictionary d'une manière si étrange? – unbeli

+3

comment est déclaré/défini dataTable? –

Répondre

0

D'après ce que je comprends:

-(NSMutableArray*) getArrayOfDictionaries{ 
    int nRows=somenumber; 
    int nColumns=someOthernumber; 
    char **azResult=someArrayOfStrings; 

    NSMutableArray *dataTable=[[NSMutableArray alloc] init]; 
    for (int i = 1; i < nRows; i++) 
    { 
     NSMutableDictionary* row = [[[NSMutableDictionary alloc] initWithCapacity:nColumns]]; 
     for(int j = 0; j < nColumns; j++) 
     { 
     NSString* key = [[NSString stringWithUTF8String:azResult[j]] ]; 
     NSString* value = [[NSString stringWithUTF8String:azResult[(i*nColumns)+j]] ]; 

     [row setValue:value forKey:key]; 
     } 
     [dataTable addObject:row]; 
     //you should add the following line to avoid leaking 
     [row release]; 
    } 

    //watch for leaks 
    return [dataTable autorelease]; 
    //beyond this point dataTable will be out of scope 
} 

-(void) callingMethod { 
    //dataTable is out of scope here, you should look into arrayOfDictionaries variable 
    NSMutableArray* arrayOfDictionaries=[self getArrayOfDictionaries]; 
} 

Vous devriez regarder dans la variable locale callingMethod au lieu de dataTable qui est locale à la méthode que j'ai appelé getArrayOfDictionaries

1

Cette ligne:

NSMutableDictionary* row = [[NSMutableDictionary alloc] initWithCapacity:nColumns] ]; 

devrait utiliser la libération automatique:

NSMutableDictionary* row = [[[NSMutableDictionary alloc] initWithCapacity:nColumns] ] autorelease];