使用 NSMutableArray 的二维数组 [英] 2D arrays using NSMutableArray

查看:23
本文介绍了使用 NSMutableArray 的二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 Objective-C 中创建一个可变的二维数组.

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

例如我有:

NSMutableArray *sections;
NSMutableArray *rows;

sections 中的每一项都由一个数组 rows 组成.rows 是一个包含对象的数组.

Each item in sections consists of an array rows. rows is an array that contains objects.

我想做这样的事情:

[ sections[i] addObject: objectToAdd]; //I want to add a new row

为了有这样的东西:第 0 节,行:obj1、obj2、obj3第 1 部分,行:obj4、obj5、obj6、obj 7...

In order have something like this: section 0, rows: obj1, obj2, obj3 section 1, rows: obj4, obj5, obj6, obj 7...

有没有办法在 Objective-C 中做到这一点?

Is there a way to do that in Objective-C?

推荐答案

首先,您必须在使用前分配并初始化您的对象,例如:NSMutableArray *sections = [[NSMutableArray alloc] initWithCapacity:10]; 对于行,每个行需要一个对象,而不是单个 NSMutableArray * rows;

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;

其次,取决于您是否使用 Xcode 4.4+(它引入了下标,又名 section[i] & section[i] = …)必须使用 [sections objectAtIndex:i] 读取和 [section replaceObjectAtIndex:i withObject: objectToAdd] 写入.

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.

第三,数组不能有空洞,即obj1、nil、obj2.您必须为每个索引提供实际对象.如果你确实需要什么都不放,你可以使用 NSNull 对象.

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.

此外,不要忘记您还可以将 Objective-C 对象存储在普通的 C 数组中:

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

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

这篇关于使用 NSMutableArray 的二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆