NSArray 添加元素 [英] NSArray adding elements

查看:266
本文介绍了NSArray 添加元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须创建一个动态的 NSArray,也就是说,我不知道数组的大小或数组将包含哪些元素.元素需要动态添加到数组中.我查看了 NSArray 类参考.有一个方法叫做arrayWithObjects,应该在初始化数组本身的时候使用.但我不知道如何实现我需要做的事情.

I have to create a dynamic NSArray, that is, I don't know the size of the array or what elements the array is going to have. The elements need to be added to the array dynamically. I looked at the NSArray class reference. There is a method called arrayWithObjects, which should be used at the time of initializing the array itself. But I don't know how to achieve what I need to do.

我需要做一些如下的事情:

I need to do some thing like the following:

NSArray *stringArray = [[NSArray init] alloc] ;  
for (int i = 0; i < data.size; i++){  
    stringArray.at(i) = getData(i);
}

推荐答案

如果您创建一个 NSArray,您将无法向其中添加元素,因为它是不可变的.您应该尝试使用 NSMutableArray 代替.

If you create an NSArray you won't be able to add elements to it, since it's immutable. You should try using NSMutableArray instead.

此外,您颠倒了 allocinit 的顺序.alloc 创建一个实例,init 初始化它.

Also, you inverted the order of alloc and init. alloc creates an instance and init initializes it.

代码看起来像这样(假设 getData 是一个全局函数):

The code would look something like this (assuming getData is a global function):

NSMutableArray *stringArray = [[NSMutableArray alloc] init];
for(int i=0; i< data.size; i++){
   [stringArray addObject:getData(i)];
}

这篇关于NSArray 添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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