Search code examples
iosxcodensmutablearrayuicontrol

Managing UIControls in NSMutableArray


I have an NSMutableArray.

I create a UIControl (say UISlider) and add it to this array in a for loop.

for (int i=0; i<totalSlider; i++) {

UISlider *tmpSlider = [[UISlider alloc] initWithRect:CGRect(0,0,200,40)];

[myArray addObject: tmpSlider];

}

This works ok. I am able to refer to it by

UISlider *tmpSlider = [myArray objectAtIndex:j];

But how to remove and release these objects individually while maintaining the remaining sliders in that array?

for example, there are 10 sliders in this array. So I want to remove slider at index 5. How to go about doing this? Thanks.


Solution

  • First of all, you have created all the UISliders in a stack, on top of each one.

    as your co-ordinates are same CGRect(0,0,200,40)];

    So you will be seeing only one of them.

    Now if you want to remove any one of them simply use

    [myArray removeObjectAtIndex:5];
    

    EDIT:

    An extract from Jed's answer.

    Like NSArray, instances of NSMutableArray maintain strong references to their contents. If you do not use garbage collection, when you add an object to an array, the object receives a retain message. When an object is removed from a mutable array, it receives a release message. If there are no further references to the object, this means that the object is deallocated. If your program keeps a reference to such an object, the reference will become invalid unless you send the object a retain message before it’s removed from the array.