8

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 ?

Dilip Manek
  • 9,095
  • 5
  • 44
  • 56
Bhavin_m
  • 2,746
  • 3
  • 30
  • 49
  • 2
    No. NSArray is static as it is, so you wouldn't even be able to add anything to it, left alone shuffling the entries. Though 'NSMutableArray' has a function `sortUsingSelector`. With this method, you could determine your own sorting order. – ATaylor Mar 04 '13 at 11:26
  • @ATaylor : is it possible in NSMutableArray ?? – Bhavin_m Mar 04 '13 at 11:28
  • @B.M.W. yes its possible in NSMutableArray.. – Aman Aggarwal Mar 04 '13 at 11:28
  • possible duplicate of [What's the Best Way to Shuffle an NSMutableArray?](http://stackoverflow.com/questions/56648/whats-the-best-way-to-shuffle-an-nsmutablearray) – Monolo Apr 18 '13 at 08:23

2 Answers2

8

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

Community
  • 1
  • 1
HDdeveloper
  • 4,396
  • 6
  • 40
  • 65
7

Your array must be an instance of a NSMutableArray otherwise write methods are not allowed (NSArray is read only)

Use the following method :

- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject

you will need a temporary storage for storing the replaces object :

id tempObj = [testArray objectAtIndex:index];
[testArray replaceObjectAtIndex:index withObject:[testArray objectAtIndex:otherIndex]];
[testArray replaceObjectAtIndex:otherIndex withObject:tempObj];
giorashc
  • 13,691
  • 3
  • 35
  • 71
  • 20
    You can use `exchangeObjectAtIndex:withObjectAtIndex:`, then you don't need a temporary object. – Martin R Mar 04 '13 at 11:43
  • 2
    Hi @MartinR have you considered moving your comment into an answer post, this is really the acceptable way to do this. Thanks for pointing out that API! – Daniel Galasko Jul 31 '14 at 07:57