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 ?
arrays can't contain nil. There is a special object, NSNull ( [NSNull null] ), that serves as a placeholder for nil.
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.
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.
NSArray(NSCoder) A constructor that initializes the object from the data stored in the unarchiver object.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With