MultiDimensional Array in Objective c

前端 未结 3 797
臣服心动
臣服心动 2021-01-03 15:43

EveryBody..

i want to create one 8*8 dimensional array in objective c..

(
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0         


        
相关标签:
3条回答
  • 2021-01-03 15:46

    To create a constant 2d array containing integers,simply do something like:

    NSArray *array;
    array = @[@[@1, @7, @4, @11],@[@2, @6, @9]];
    

    This creates an array

    1 7 4 11
    2 6 9
    
    0 讨论(0)
  • 2021-01-03 16:00

    In C:

    int **array = (int**)calloc(8, sizeof(int*));
    for (int i=0; i<8; i++) array[i] = (int*)calloc(8, sizeof(int));
    // use your array
    // cleaning:
    for (int i=0; i<8; i++) free(array[i]);
    free(array);
    
    0 讨论(0)
  • 2021-01-03 16:13

    In Objective-C:

    array = [[NSMutableArray alloc] init];
    
    for (int i = 0; i < 8; i++) {
        NSMutableArray *subArray = [[NSMutableArray alloc] init];
        for (int j = 0; j < 8; j++) {
            [subArray addObject:[NSNumber numberWithInt:0]]; 
        }
        [array addObject:subArray];
        [subArray release];
    }
    

    (array is an instance variable, that has to be added to your header file and released in you dealloc method)

    To retrieve a value at a certain position you could write a method like this:

    - (int)valueAtRow:(int)row andColumn:(int)col {
        NSMutableArray *subArray = [array objectAtIndex:row];
        return [[subArray objectAtIndex:col] intValue];
    }
    

    === UPDATE ===

    To remove an object you could do this:

    - (void)removeObjectAtRow:(int)row andColumn:(int)col {
        NSMutableArray *subArray = [array objectAtIndex:row];
        [subArray removeObjectAtIndex:col];
    }
    

    You have to be careful though, because removing objects will change the structure of the array (e.g. the row where you removed an object will have only 7 items after the removal. So you might want to think about leaving the structure intact and set the values that you want to delete to a value that you normally don't use:

    - (void)removeObjectAtRow:(int)row andColumn:(int)col {
        NSMutableArray *subArray = [array objectAtIndex:row];
        [subArray replaceObjectAtIndex:col withObject:[NSNumber numberWithInt:-999]];
    }
    
    0 讨论(0)
提交回复
热议问题