NSArray adding elements

爷,独闯天下 提交于 2019-12-02 20:05:25
pgb

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.

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

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)];
}
Danil

Here is another way to add object in array if you are working with immutable array. Which is thread safe.

You can use arrayByAddingObject method. Some times it's much better. Here is discussion about it: NSMutableArray vs NSArray which is better

Convert your NSArray to NSMutableArray, and then you can add values dynamically:

NSMutableArray *mutableStringArray = [stringArray mutableCopy];
[mutableStringArray addObject:@"theNewElement"];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!