5

I have a NSMutableArray that is loaded with values.

Later in the application, I need to change the values of one of the elements in the array.

How do I accomplish this?

thanks tony

4 Answers 4

16

Take a look at the class reference instance methods:

http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSMutableArray_Class/Reference/Reference.html

You can use:

replaceObjectAtIndex:withObject: given you know the index of the object. replaceObjectsAtIndexes:withObjects: to replace multiple objects at once.

0
4

Call -[NSMutableArray replaceObjectAtIndex:withObject:]. Or, if the object in the array is mutable, just grab it with -objectAtIndex: and modify its properties directly.

3
  • I find these answers a bit off topic actually. The OP seemed to want to update one property of an object, not the whole object. If that was the case, is there a way to do that without replacing the whole object? I specifically placed my comment here, Ole..since you're the man..
    – whyoz
    Commented Jul 9, 2015 at 1:02
  • 1
    @whyoz: As I wrote, just ask the array for the object and then modify its properties. MyObject *obj = array[index]; obj.myProperty = newValue;. Commented Jul 9, 2015 at 16:17
  • 1
    I guess what I meant to say is that I found the "accepted answer" a bit off topic, but it's all about what the OP meant by "change the values of one of the elements." If you want to change all the values and replace them with an existing object's values, then replaceObjectAtIndex is helpful. If you need to change some of the values, then you need to access each property that needs changing in the way Ole explains in greater detail in the preceding comment. Some readers of this post might not know what you meant by objectAtIndex and just pass by your answer, even though it's what they need.
    – whyoz
    Commented Jul 10, 2015 at 17:56
1

You would probably want to use 'replaceObjectAtIndex:withObject:' for replacing the object itself.

1

refer following link. It may help you

http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/replaceObjectAtIndex:withObject:

From that you can use replaceObjectAtIndex:withObject: or
replaceObjectsAtIndexes:withObjects: for replacing objects.

just you have to know the index of objects.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.