MultiDimensional Array in Objective c

前端 未结 3 841
臣服心动
臣服心动 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 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]];
    }
    

提交回复
热议问题