在Objective-C中创建二维数组

dra*_*ion 24 objective-c

什么是在Objective-C中声明二维数组的最简单方法?我正在从网站的文本文件中读取数字矩阵,并希望获取数据并将其放入3x3矩阵中.

一旦我将URL读入字符串,我创建一个NSArray并使用componentsSeparatedByString方法去除回车换行符并创建每个单独的行.然后,我得到新数组中行数的计数,以获得每行的各个值.这将为mw提供一个包含字符串的数组,而不是一行包含三个单独的值.我只需要能够获取这些值并创建一个二维数组.

Fer*_*cio 47

如果它不需要是一个对象,你可以使用:

float matrix[3][3];
Run Code Online (Sandbox Code Playgroud)

定义3x3浮点数组.


小智 43

您可以使用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];
Run Code Online (Sandbox Code Playgroud)

我希望你从上面的例子中得到答案.

干杯,拉克西特


atb*_*r11 16

这也有效:

    NSArray *myArray = @[
                            @[ @1, @2, @3, @4],
                            @[ @1, @2, @3, @4],
                            @[ @1, @2, @3, @4],
                            @[ @1, @2, @3, @4],
                       ];
Run Code Online (Sandbox Code Playgroud)

在这种情况下,它是一个4x4阵列,其中只有数字.


Jer*_*myP 5

我并不完全确定你在寻找什么,但我对二维数组的处理方法是创建一个新类来封装它.注意,下面的内容直接输入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
Run Code Online (Sandbox Code Playgroud)