how to add object at specific index and also remove another object from NSMutableArray?

StackOverflow https://stackoverflow.com/questions/23631180

  •  21-07-2023
  •  | 
  •  

Question

hello friends i'm new in ios development. i want to add object at specified index for that i code here.

arrNotificationTime = [NSMutableArray arrayWithCapacity:arrNotificationView.count];

for (int i=0; i<arrNotificationView.count; i++)
{
    [arrNotificationTime addObject:[NSNull null]];
}
NSLog(@"Time count == %d",[arrNotificationTime count]);
[arrNotificationTime replaceObjectAtIndex:btnNotificationTime.tag withObject:btnNotificationTime.titleLabel.text];

and it work perfectly but i also want to remove another or the same object from this array or also print this array is not work for that i code here.

NSLog(@"arrNotificationTime == %@",arrNotificationTime);
[arrNotificationTime removeObjectAtIndex:[btn tag]];

when i nslog the array it will crash the application. The error report is.

2014-05-13 17:52:09.973 TOPDesign[1057:11303] arrNotificationTime count = 0
2014-05-13 17:52:09.974 TOPDesign[1057:11303] arrNotificationTime == (
)
2014-05-13 17:52:09.975 TOPDesign[1057:11303] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM removeObjectAtIndex:]: index 1 beyond bounds for empty array'
*** First throw call stack:
(0x15ae012 0x12bbe7e 0x15501c4 0xc6ec 0x12cf705 0x2032c0 0x203258 0x2c4021 0x2c457f 0x2c36e8 0x4c71d3 0x1576afe 0x1576a3d 0x15547c2 0x1553f44 0x1553e1b 0x260f7e3 0x260f668 0x1ffffc 0x2592 0x24c5)
libc++abi.dylib: terminate called throwing an exception
(lldb) 
Was it helpful?

Solution

You can't remove any object in empty array. so it crashes.

you must use like this

 [arrNotificationTime count] is total count of your array

suppose you have 10 items

you btn tag should be within 0 to 9. if you access the 11th item then it will crash. to avoid it. you must use like this

if([arrNotificationTime count]>[btn tag]){


    [arrNotificationTime removeObjectAtIndex:[btn tag]];


}

OTHER TIPS

This is for adding object in specific index in array.

[YourArray insertObject:@"" atIndex:0];

This is for remove object at specific object.

[YourArray removeObjectAtIndex:5];

Hope this code is useful for you.

In your arrNotificationTime array no object and you remove the object.so app is crashed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top