3

I have an NSMutableArray of UIViews that I put in UIScrollView which is responsible for putting them in order. Right now I have this code for changing two UIViews positions with each other:

UIView *viewToBeChanged = [views objectAtIndex:self.page];
UIView *previousView = [views objectAtIndex:previousPage];

[views removeObjectAtIndex:self.page];
[views removeObjectAtIndex:previousPage];

[views insertObject:viewToBeChanged atIndex:previousPage];
[views insertObject:previousView atIndex:self.page];

Is there a better way to change the position of an object in NSMutableArray with another one? Thanks!

2
  • Use this exchangeObjectAtIndex:withObjectAtIndex: Commented Aug 19, 2013 at 13:27
  • You can use replaceObjectAtIndex: withObject: or exchangeObjectAtIndex:withObjectAtIndex: or replaceObjectAtIndex: withObjectAtIndex:as per your requirement. Commented Aug 19, 2013 at 13:29

1 Answer 1

5

You can use replaceObjectAtIndex:i method

 [array replaceObjectAtIndex:i withObject:newObj];

You can also use exchangeObjectAtIndex:withObjectAtIndex:

  [array exchangeObjectAtIndex:i withObjectAtIndex:j];
Sign up to request clarification or add additional context in comments.

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.