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

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

问题描述

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



例如我有:

  NSMutableArray * sections; 
NSMutableArray * rows;

中的每个项目都包含一个数组 rows rows 是一个包含对象的数组。



我想这样做:

  [sections [i] addObject:objectToAdd]; //我想添加一个新行

0,rows:obj1,obj2,obj3
section 1,rows:obj4,obj5,obj6,obj 7 ...



有办法首先,你必须在使用之前分配和初始化你的对象,例如:<$ c $

c> NSMutableArray * sections = [[NSMutableArray alloc] initWithCapacity:10]; 对于行,你需要一个对象,而不是单个 NSMutableArray * c $ c>



其次,根据你是否使用Xcode 4.4+(引入下标,aka section [i] [sections objectAtIndex:i] & 用于读取



第三,数组不能有孔,用于读取和 [section replaceObjectAtIndex:i withObject:objectToAdd] NSNull 对象。



此外,不要忘记你也可以存储Objective-C对象在纯C数组中:

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


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

For example I have:

NSMutableArray *sections;
NSMutableArray *rows;

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

And I want to do something like this:

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

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

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

解决方案

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;

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

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