2010-12-06 5 views
21

Quel est le moyen le plus simple de déclarer un tableau bidimensionnel en Objective-C? Je lis une matrice de nombres à partir d'un fichier texte d'un site Web et je veux prendre les données et les placer dans une matrice 3x3.Création d'un tableau bidimensionnel dans Objective-C

Une fois que j'ai lu l'URL dans une chaîne, je crée un NSArray et utilise la méthode componentsSeparatedByString pour supprimer le flux de retour chariot et créer chaque ligne individuelle. J'ai ensuite le nombre de lignes dans le nouveau tableau pour obtenir les valeurs individuelles à chaque ligne. Cela donnera à mw un tableau avec une chaîne de caractères, pas une rangée de trois valeurs individuelles. Je dois juste être capable de prendre ces valeurs et créer un tableau à deux dimensions.

+4

Xcode est juste un IDE. Ceci est une question liée à Objective-C/Cocoa – vikingosegundo

+3

Ce n'est pas non plus du cacao tactile ni de l'iPhone spécifique. Seul objectif c – uchuugaka

Répondre

45

Si elle n'a pas besoin d'être un objet que vous pouvez utiliser:

float matrix[3][3]; 

pour définir une matrice de 3x3 de flotteurs.

+1

oui, simple et propre! – plan9assembler

+1

Je pense que c'est la bonne réponse parce qu'il regarde "la matrice des nombres d'un fichier texte". – seixasfelipe

42

Vous pouvez utiliser la matrice de style Objective C.

NSMutableArray *dataArray = [[NSMutableArray alloc] initWithCapacity: 3]; 

[dataArray insertObject:[NSMutableArray arrayWithObjects:@"0",@"0",@"0",nil] atIndex:0]; 
[dataArray insertObject:[NSMutableArray arrayWithObjects:@"0",@"0",@"0",nil] atIndex:1]; 
[dataArray insertObject:[NSMutableArray arrayWithObjects:@"0",@"0",@"0",nil] atIndex:2]; 

J'espère que vous obtenez votre réponse de l'exemple ci-dessus.

Cheers, Raxit

+0

Comment obtiendriez-vous alors à chaque objet individuel? – Rob85

5

Je ne suis pas absolument certain de ce que vous cherchez, mais mon approche d'un tableau à deux dimensions serait de créer une nouvelle classe pour encapsuler. NB: le texte ci-dessous a été tapé directement dans la boîte de réponse StackOverflow afin qu'il ne soit pas compilé ou testé.

@interface TwoDArray : NSObject 
{ 
@private 
    NSArray* backingStore; 
    size_t numRows; 
    size_t numCols; 
} 

// values is a linear array in row major order 
-(id) initWithRows: (size_t) rows cols: (size_t) cols values: (NSArray*) values; 
-(id) objectAtRow: (size_t) row col: (size_t) col; 

@end 

@implementation TwoDArray 


-(id) initWithRows: (size_t) rows cols: (size_t) cols values: (NSArray*) values 
{ 
    self = [super init]; 
    if (self != nil) 
    { 
     if (rows * cols != [values length]) 
     { 
      // the values are not the right size for the array 
      [self release]; 
      return nil; 
     } 
     numRows = rows; 
     numCols = cols; 
     backingStore = [values copy]; 
    } 
    return self; 
} 

-(void) dealloc 
{ 
    [backingStore release]; 
    [super dealloc]; 
} 

-(id) objectAtRow: (size_t) row col: (size_t) col 
{ 
    if (col >= numCols) 
    { 
     // raise same exception as index out of bounds on NSArray. 
     // Don't need to check the row because if it's too big the 
     // retrieval from the backing store will throw an exception. 
    } 
    size_t index = row * numCols + col; 
    return [backingStore objectAtIndex: index]; 
} 

@end 
16

Cela fonctionne également:

NSArray *myArray = @[ 
          @[ @1, @2, @3, @4], 
          @[ @1, @2, @3, @4], 
          @[ @1, @2, @3, @4], 
          @[ @1, @2, @3, @4], 
         ]; 

Dans ce cas, il est un tableau de 4x4 avec juste des chiffres qu'il contient.

1

Tout d'abord vous avez défini un NSMutableDictionary sur .h fichier

  @interface MSRCommonLogic : NSObject 
      { 
       NSMutableDictionary *twoDimensionArray; 
      } 

      then have to use following functions in .m file 


      - (void)setValuesToArray :(int)rows cols:(int) col value:(id)value 
      { 
       if(!twoDimensionArray) 
       { 
        twoDimensionArray =[[NSMutableDictionary alloc]init]; 
       } 

       NSString *strKey=[NSString stringWithFormat:@"%dVs%d",rows,col]; 
       [twoDimensionArray setObject:value forKey:strKey]; 

      } 

      - (id)getValueFromArray :(int)rows cols:(int) col 
      { 
       NSString *strKey=[NSString stringWithFormat:@"%dVs%d",rows,col]; 
       return [twoDimensionArray valueForKey:strKey]; 
      } 


      - (void)printTwoDArray:(int)rows cols:(int) cols 
      { 
       NSString *[email protected]""; 
       strAllsValuesToprint=[strAllsValuesToprint stringByAppendingString:@"\n"]; 
       for (int row = 0; row < rows; row++) { 
        for (int col = 0; col < cols; col++) { 

         NSString *strV=[self getValueFromArray:row cols:col]; 
         strAllsValuesToprint=[strAllsValuesToprint stringByAppendingString:[NSString stringWithFormat:@"%@",strV]]; 
         strAllsValuesToprint=[strAllsValuesToprint stringByAppendingString:@"\t"]; 
        } 
        strAllsValuesToprint= [strAllsValuesToprint stringByAppendingString:@"\n"]; 
       } 

       NSLog(@"%@",strAllsValuesToprint); 

      } 
+0

Très bon moyen d'implémenter un tableau 2D en Objective-C. Mais c'est probablement une bonne idée d'utiliser 'NSMutableArray' au lieu de' NSDictionary'. 'NSDictionary' est un peu plus lent selon [cette réponse] (https://stackoverflow.com/a/10545362/5843393). –

1

Hope this helps. Ce est par exemple à quel point vous pouvez initial tableau 2D de int dans le code (Objectif d'entreprise C)

int **p; 
p = (int **) malloc(Nrow*sizeof(int*)); 
for(int i =0;i<Nrow;i++) 
{ 
    p[i] = (int*)malloc(Ncol*sizeof(int)); 
} 
//put something in 
for(int i =0;i<Nrow;i++) 
{ 
    p[i][i] = i*i; 
    NSLog(@" Number:%d value:%d",i, p[i][i]); 
} 

//free pointer after use 
for(int i=0;i<Nrow;i++) 
{ 
    p[i]=nil; 
    //free(p[i]); 
    NSLog(@" Number:%d",i); 
} 
//free(**p); 
p = nil; 
Questions connexes