NSArray adding elements

后端 未结 3 658
深忆病人
深忆病人 2021-02-02 06:33

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 dynamica

相关标签:
3条回答
  • 2021-02-02 07:27

    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

    0 讨论(0)
  • 2021-02-02 07:32

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

    NSMutableArray *mutableStringArray = [stringArray mutableCopy];
    [mutableStringArray addObject:@"theNewElement"];
    
    0 讨论(0)
  • 2021-02-02 07:33

    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)];
    }
    
    0 讨论(0)
提交回复
热议问题