Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap value index in NSArray

Tags:

iphone

nsarray

I have NSArray. I have some value inside that array.

NSArray *testArray = [NSArray arrayWithObjects:@"Test 1", @"Test 2", @"Test 3", @"Test 4", @"Test 5", nil];
NSLog(@"%@", testArray);

Result is like bellow :

(
"Test 1",
"Test 2",
"Test 3",
"Test 4",
"Test 5"
)

Now I want the result like this :

(
"Test 3",
"Test 5",
"Test 1",
"Test 2",
"Test 4"
)

Is there any way to do it without re-initialize the array? Can I swap the value of this array ?

like image 300
Bhavin_m Avatar asked Mar 04 '13 11:03

Bhavin_m


People also ask

Can NSArray contain nil?

arrays can't contain nil. There is a special object, NSNull ( [NSNull null] ), that serves as a placeholder for nil.

Is NSArray ordered?

In Objective-C, arrays take the form of the NSArray class. An NSArray represents an ordered collection of objects. This distinction of being an ordered collection is what makes NSArray the go-to class that it is.

How do you declare NSArray in Objective-C?

Creating NSArray Objects Using Array Literals In addition to the provided initializers, such as initWithObjects: , you can create an NSArray object using an array literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:count:) method.

What is NSArray?

NSArray(NSCoder) A constructor that initializes the object from the data stored in the unarchiver object.


1 Answers

Use NSMutableArray to swap two objects.

- exchangeObjectAtIndex:withObjectAtIndex:

This exchanges the objects in the array at given indexes(idx1 and idx2)

idx1
The index of the object with which to replace the object at index idx2.

idx2
The index of the object with which to replace the object at index idx1.

SWIFT

func exchangeObjectAtIndex(_ idx1: Int,
         withObjectAtIndex idx2: Int)

OBJECTIVE-C Use a NSMutableArray

  - (void)exchangeObjectAtIndex:(NSUInteger)idx1
                withObjectAtIndex:(NSUInteger)idx2

Swapping elements in an NSMutableArray

like image 139
HDdeveloper Avatar answered Sep 18 '22 15:09

HDdeveloper