2010-12-06 10 views
21

Objective-C에서 2 차원 배열을 선언하는 가장 쉬운 방법은 무엇입니까? 나는 웹 사이트에서 텍스트 파일의 숫자 행렬을 읽고 데이터를 가져 와서 3x3 행렬에 넣기를 원합니다.Objective-C에서 2 차원 배열 만들기

일단 URL로 문자열을 읽으면 NSArray를 만들고 componentsSeparatedByString 메서드를 사용하여 캐리지 리턴 줄 바꿈을 제거하고 개별 행을 만듭니다. 그런 다음 새 배열의 행 수를 계산하여 각 행의 개별 값을 가져옵니다. 이렇게하면 mw에 3 개의 개별 값 행이 아닌 일련의 문자가있는 배열이 제공됩니다. 난 그냥 이러한 값을 받아 2 차원 배열을 만들 수 있어야합니다. 당신이 사용할 수있는 대상이 필요하지 않는 경우

+4

엑스 코드 그냥 IDE이다 초기 수있는 방법을 단지 예입니다. 이것은 Objective-C/Cocoa 관련 질문입니다. – vikingosegundo

+3

또한 코코아 터치도 아니고 iPhone 고유도 아닙니다. 오직 객관적인 C – uchuugaka

답변

45

:

float matrix[3][3]; 

는 수레의 3 × 3 배열을 정의 할 수 있습니다.

+1

예, 간단하고 깨끗한! – plan9assembler

+1

"텍스트 파일의 숫자 행렬"을보고 있기 때문에 이것이 올바른 대답이라고 생각합니다. – seixasfelipe

42

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

위의 예에서 답을 얻길 바랍니다.

난 당신이 찾고있는 것을 절대적으로 확실하지 않다 건배, Raxit

+0

그러면 각각의 개체를 어떻게 얻을 수 있습니까? – Rob85

5

하지만 두 차원 배열에 대한 나의 접근 방식을 캡슐화하는 새로운 클래스를 생성하는 것입니다. NB는 StackOverflow 응답 박스에 직접 입력되었으므로 컴파일되거나 테스트되지 않습니다.

@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

이것은 또한 작동합니다 :이 경우

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

를 그것은 단지 숫자 4 × 4 배열입니다.

1

먼저 .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

Objective-C에서 2D 배열을 구현하는 가장 좋은 방법입니다. 그러나 아마도 NSDictionary 대신 NSMutableArray를 사용하는 것이 좋습니다. NSDictionary는 [이 답변] (https://stackoverflow.com/a/10545362/5843393)에 따르면 조금 느립니다. –

1

희망이 도움에 NSMutableDictionary를 설정합니다. 이것은 당신이 코드 INT의 2 차원 배열 (목적 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;