为 iPhone 开发初始化多维 NSArray

发布于 2024-09-24 10:55:44 字数 387 浏览 0 评论 0原文

我从 iPhone 开发开始,需要使用多维数组。

我使用以下方法初始化它:

NSArray *multi=[NSArray 
  arrayWithObjects:[NSMutableArray arrayWithCapacity:13],
  [NSMutableArray array],nil];

但是当我尝试像这样向第 n 个单元格分配值时:

[[multi objectAtIndex:4] addObject:@"val"];

应用程序挂起,因为索引 4 超出了范围 [0 .. 1]

哪种是初始化多阵列的正确方法?预先感谢并致以问候。

I'm starting with iPhone development and I need to use a multidimensional array.

I initialize it using:

NSArray *multi=[NSArray 
  arrayWithObjects:[NSMutableArray arrayWithCapacity:13],
  [NSMutableArray array],nil];

But when I try to assign values to n-th cell like this:

[[multi objectAtIndex:4] addObject:@"val"];

The app hangs because index 4 is beyond the bounds [0 .. 1].

Which is the correct way to init my multi-array? Thanks in advance and greetings.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

倾`听者〃 2024-10-01 10:55:44

我猜你想创建一个 NSMutableArrays 的 NSMutableArray:

NSMutableArray *multi = [NSMutableArray arrayWithCapacity: 13];
for (int i = 0; i != 13; i++)
{
    NSMutableArray *array = [NSMutableArray arrayWithCapacity: 10];
    [multi insertObject: array atIndex: 0];
}

之后,你的调用是有效的。

编辑:作为旁注,容量!=计数,就像 .NET 或 C++ 的 STL 中的情况(如果您了解这些)。

I guess you want to create a NSMutableArray of NSMutableArrays:

NSMutableArray *multi = [NSMutableArray arrayWithCapacity: 13];
for (int i = 0; i != 13; i++)
{
    NSMutableArray *array = [NSMutableArray arrayWithCapacity: 10];
    [multi insertObject: array atIndex: 0];
}

After that, your call is valid.

EDIT: as a side note, capacity != count, as would be in .NET or C++'s STL if you know these.

清秋悲枫 2024-10-01 10:55:44

您所做的是创建一个包含两个对象的数组:另外两个数组。您实际上是在请求这个“超级数组”中的第五个对象,这是行不通的,因为没有。

顺便说一下,即使你创建了一个指定容量的数组,它仍然是空的。指定容量只是为数组分配足够的内存来容纳至少给定数量的对象。如果您不添加任何对象,如果您要求添加第 10 个对象,它仍然会使您的应用程序崩溃。

What you did is creating an array containing two objects: two other arrays. You're actually asking for the 5th object within this "super-array", which won't work because there is none.

By the way, even if you create an array specifying a capacity, it is still empty. Specifying a capacity merely allocs enough memory for the array to hold at least the given number of objects. If you add no objects, it would still make your app crash if you'd ask for, say, the 10th object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文