Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add object at first index of NSArray

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.

like image 711
Joker Avatar asked Dec 13 '12 06:12

Joker


People also ask

How do you declare NSArray in Objective C?

In Objective-C, the compiler generates code that makes an underlying call to the init(objects:count:) method. id objects[] = { someObject, @"Hello, World!", @42 }; NSUInteger count = sizeof(objects) / sizeof(id); NSArray *array = [NSArray arrayWithObjects:objects count:count];

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

What's a difference between NSArray and NSSet?

The main difference is that NSArray is for an ordered collection and NSSet is for an unordered collection. There are several articles out there that talk about the difference in speed between the two, like this one. If you're iterating through an unordered collection, NSSet is great.

Can NSArray contain nil?

arrays can't contain nil.


3 Answers

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)
like image 106
arthankamal Avatar answered Oct 23 '22 09:10

arthankamal


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.

like image 32
Shad Avatar answered Oct 23 '22 07:10

Shad


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.

like image 36
Chris Conover Avatar answered Oct 23 '22 08:10

Chris Conover