25

Whats the easiest way to declare a two dimensional array in Objective-C? I am reading an matrix of numbers from a text file from a website and want to take the data and place it into a 3x3 matrix.

Once I read the URL into a string, I create an NSArray and use the componentsSeparatedByString method to strip of the carriage return line feed and create each individual row. I then get the count of the number of lines in the new array to get the individual values at each row. This will give mw an array with a string of characters, not a row of three individual values. I just need to be able to take these values and create a two dimensional array.

2
  • 4
    xcode is just an IDE. this is an Objective-C/Cocoa related question Commented Dec 6, 2010 at 3:17
  • 3
    It's also not cocoa touch nor iPhone specific. Only objective c Commented Sep 10, 2013 at 22:19

6 Answers 6

47

If it doesn't need to be an object you can use:

float matrix[3][3];

to define a 3x3 array of floats.

Sign up to request clarification or add additional context in comments.

1 Comment

I think this is the right answer because he's looking at "matrix of numbers from a text file".
43

You can use the Objective C style array.

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

I hope you get your answer from the above example.

Cheers, Raxit

2 Comments

How would you then get at each individual object?
@Rob85 The normal way should work: dataArray[i][j]
19

This will also work:

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

In this case it is a 4x4 array with just numbers in it.

Comments

6

I'm not absolutely certain what you are looking for, but my approach to a two dimensional array would be to create a new class to encapsulate it. NB the below was typed directly into the StackOverflow answer box so it is not compiled or tested.

@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

Comments

1

First you to have set An NSMutableDictionary on .h file

            @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 *strAllsValuesToprint=@"";
                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);

            }

1 Comment

Very good way to implement 2D array in Objective-C. But probably it is a good idea to use NSMutableArray instead of NSDictionary. NSDictionary is a little bit slower according to this answer.
1

Hope this helps. This is just example how you can initial 2d array of int in code (Objective C works)

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.