2D arrays using NSMutableArray

后端 未结 8 845
夕颜
夕颜 2020-11-29 21:41

I need to create a mutable two-dimensional array in Objective-C.

For example I have:

NSMutableArray *sections;
NSMutableArray *rows;
<
8条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 22:07

    First, you must allocate and initialize your objects before use, something like: NSMutableArray * sections = [[NSMutableArray alloc] initWithCapacity:10]; For the rows, you need one object for each, not a single NSMutableArray * rows;

    Second, depending on whether you're using Xcode 4.4+ (which introduced subscripting, a.k.a section[i] & section[i] = …) you may have to use [sections objectAtIndex:i] for reading and [section replaceObjectAtIndex:i withObject: objectToAdd] for writing.

    Third, an array cannot have holes, i.e., obj1, nil, obj2. You must provide actual object to every index. If you do need to put nothing, you can use NSNull object.

    Moreover, don't forget that you can also store Objective-C objects in plain C arrays:

    id table[lnum][rnum];
    table[i][j] = myObj;
    

提交回复
热议问题