How to add object at first index of NSArray

后端 未结 10 667
离开以前
离开以前 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:14

    NSArray is not dyanamic to solve your purpose you have to use NSMutableArray. Refer the following method

    - (void)insertObject:(id)anObject atIndex:(NSUInteger)index;
    
    0 讨论(0)
  • 2021-02-01 06:17

    I know that we have six answers for insertObject, and one for creating a(n) NSMutableArray array and then calling addObject, but there is also this:

    myArray = [@[@"ALL ITEMS"] arrayByAddingObjectsFromArray:myArray];
    

    I haven't profiled either though.

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

    Take a look at the insertObject:atIndex: method of the NSMutableArray class.To add an object to the front of the array, use 0 as the index:

    [myMutableArray insertObject:myObject atIndex:0];
    
    0 讨论(0)
  • 2021-02-01 06:20

    NSArray is immutable array you can't modify it in run time. Use NSMutableArray

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

    As you are allready having 10 objects in your array,and you need to add another item at index 11...so,you must try this.... hope this helps..

    NSMutableArray *yourArray = [[NSMutableArray alloc] initWithCapacity:11];
    [yourArray insertObject:@"All Items" atIndex:0];
    
    0 讨论(0)
  • 2021-02-01 06:24

    Swift 3:

    func addObject(){
        var arrayName:[String] = ["Name1", "Name2", "Name3"]
        arrayName.insert("Name0", at: 0)
        print("---> ",arrayName)
    }
    
    Output:
    ---> ["Name0","Name1", "Name2", "Name3"]
    
    0 讨论(0)
提交回复
热议问题