4

I have NSMutableArray. There are for example such objects: 0, 1, 2. How can I replace object 0 into index where object 2. In result I want array with objects: 1, 2, 0. Thanks.

3 Answers 3

8

@trojanfoe, there is a simple mistake in your answer.

The first line of the code does not return anything as per doc. So it should be,

id object = [[array objectAtIndex:0] retain];
[array removeObjectAtIndex:0];
[array insertObject:object atIndex:2];
[object release];
Sign up to request clarification or add additional context in comments.

2 Comments

This is a comment and not an answer.
There is no need to retain and later release object because objectAtIndex returns a retained and autoreleased object.
0
[array addObject:[array objectAtIndex:0]];
[array removeObjectAtIndex:0];

Comments

0

First get a copy of the object, then remove it from index 0, then add it at index 2.

id object = [array objectAtIndex:0];
[array removeObjectAtIndex:0];
[[array insertObject:object atIndex:2];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.