objective c 2-dimensional array? [duplicate]

给你一囗甜甜゛ 提交于 2019-12-24 10:44:47

问题


I am having a bit of trouble creating a dynamically allocated two-dimensional array. If it makes a difference I am coding for ios.

I am a bit new to objective c and the memory allocation in this language is a bit confusing. I did a bit of research and come up with NSMutableArray and this link, 2D arrays using NSMutableArray, but am still confused.

What I am looking to do is create a list of rows and colunms, each row containing a dynamically created number of column objects. The number of rows is also dynamic.

If you think of the layout as a a hash map; graphically, each hash cell will contain a button and a label displayed on the screen.

EDIT:

I have,

NSMutableArray *rows;
NSMutableArray *columns;

- (void)viewDidLoad {
    rows = [[NSMutableArray alloc] init];
    columns = [[NSMutableArray alloc] init];

    //allocate memory?
}

My main question is how to allocate the memory for each entry?

EDIT2:

If anyone needed help with this I got the answer and look more to dictionaries instead of Arrays, they have lots of helpful methods.


回答1:


You cannot create 2 dimensional array with objective-c but you can use c style array, for example:

@implementation TwoDimCArray
{
    NSUInteger _array[8][8];
}

- (id)init
{
    if (self = [super init]){
        [self clearArray];
    }
    return self;
}

- (int)cellStateAtColumn:(NSInteger)column andRow:(NSInteger)row
{
    return _array[column][row];
}

- (void)setCellState:(BoardCellState)state forColumn:(NSInteger)column andRow:(NSInteger)row
{
    _array[column][row] = state;
}

- (void) clearArray
{
    memset(_array, 0, sizeof(NSUInteger) * 8 * 8);
}
@end

It works very quick when you compare it with NSArray embedded in another NSArray. Hope it help.




回答2:


So you need to create one array which will hold all of the rows. Then, for each row you need to create a new array to hold the data for that row, the number of elements in this array is the number of columns this row has.

Does that make sense? You essentially end up with an array of arrays.



来源:https://stackoverflow.com/questions/20498584/objective-c-2-dimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!