How to add object at first index of NSArray

*爱你&永不变心* 提交于 2019-12-31 09:29:10

问题


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.


回答1:


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.




回答2:


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)



回答3:


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.




回答4:


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];



回答5:


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

[array insertObject:@"YourObject" atIndex:0];



回答6:


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

[array insertObject:@"all items" atIndex:0];



回答7:


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];



回答8:


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

- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;



回答9:


Apple documents says NSMutableArray Methods

 [temp insertObject:@"all" atIndex:0];



回答10:


Swift 3:

func addObject(){
    var arrayName:[String] = ["Name1", "Name2", "Name3"]
    arrayName.insert("Name0", at: 0)
    print("---> ",arrayName)
}

Output:
---> ["Name0","Name1", "Name2", "Name3"]


来源:https://stackoverflow.com/questions/13854576/how-to-add-object-at-first-index-of-nsarray

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