How to add object at first index of NSArray

后端 未结 10 668
离开以前
离开以前 2021-02-01 06:03

I want to add @\"ALL ITEMS\" object at the first index of NSARRAY.

Initially the Array has 10 objects. After adding, the array should contains 11 objects.

相关标签:
10条回答
  • 2021-02-01 06:25

    NSArray is immutable but you can use insertObject: method of NSMutableArray class

    [array insertObject:@"all items" atIndex:0];
    
    0 讨论(0)
  • 2021-02-01 06:27

    First of all, NSArray need to be populated when it is initializing. So if you want to add some object at an array then you have to use NSMutableArray. Hope the following code will give you some idea and solution.

    NSArray *array = [[NSArray alloc] initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0", nil];
    NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
    [mutableArray addObject:@"ALL ITEMS"];
    [mutableArray addObjectsFromArray:array];
    

    The addObject method will insert the object as the last element of the NSMutableArray.

    0 讨论(0)
  • 2021-02-01 06:33

    Apple documents says NSMutableArray Methods

     [temp insertObject:@"all" atIndex:0];
    
    0 讨论(0)
  • 2021-02-01 06:38

    you can't modify NSArray for inserting and adding. you need to use NSMutableArray. If you want to insert object at specified index

    [array1 insertObject:@"ALL ITEMS" atIndex:0];

    In Swift 2.0

    array1.insertObject("ALL ITEMS", atIndex: 0)
    
    0 讨论(0)
提交回复
热议问题