2010-12-06 14 views
21

¿Cuál es la forma más fácil de declarar una matriz bidimensional en Objective-C? Estoy leyendo una matriz de números de un archivo de texto de un sitio web y quiero tomar los datos y colocarlos en una matriz de 3x3.Creación de una matriz bidimensional en Objective-C

Una vez que leo la URL en una cadena, creo una NSArray y uso el método componentsSeparatedByString para quitar la línea de retorno de carro y crear cada fila individual. Luego obtengo el recuento de la cantidad de líneas en la nueva matriz para obtener los valores individuales en cada fila. Esto le dará a mw una matriz con una cadena de caracteres, no una fila de tres valores individuales. Solo necesito poder tomar estos valores y crear una matriz bidimensional.

+4

Xcode es sólo un IDE. esta es una pregunta relacionada con Objective-C/Cocoa – vikingosegundo

+3

Tampoco es un toque de cacao ni específico para iPhone. Solo objetivo c – uchuugaka

Respuesta

45

Si no tiene por qué ser un objeto que puede utilizar:

float matrix[3][3]; 

para definir una matriz 3x3 de flotadores.

+1

¡sí, simple y limpio! – plan9assembler

+1

Creo que esta es la respuesta correcta porque está mirando "la matriz de números de un archivo de texto". – seixasfelipe

42

Puede usar la matriz de estilo 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]; 

Espero que recibas tu respuesta del ejemplo anterior.

Saludos, Raxit

+0

¿Cómo podría llegar a cada objeto individual? – Rob85

5

no estoy absolutamente seguro de lo que busca, pero mi enfoque de una matriz de dos dimensiones sería la creación de una nueva clase para encapsular la misma. NB: a continuación, se ingresó el texto directamente en el cuadro de respuesta de StackOverflow para que no se compile o pruebe.

@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

Esto también funciona:

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

En este caso se trata de una matriz 4x4 con sólo números en el mismo.

1

Primero que haya programado una NSMutableDictionary el archivo .h

  @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

Muy buena manera de implementar matriz 2D en Objective-C. Pero probablemente sea una buena idea usar 'NSMutableArray' en lugar de' NSDictionary'. 'NSDictionary' es un poco más lento de acuerdo con [esta respuesta] (https://stackoverflow.com/a/10545362/5843393). –

1

Espero que esto ayude. esto es sólo ejemplo de cómo puede 2d inicial del array de int en el código (obras Objective 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; 
Cuestiones relacionadas