Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMutableArray removeObjectAtIndex:indexPath.row crashes

I have a UITableViewController with an NSMutableArray in the header like this:

NSMutableArray *someArray;

Also I have the property declared:

@property (nonatomic, retain) NSMutableArray *someArray;

In the .m file I load the array in the method:

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    someArray = [[NSMutableArray alloc] init];

    [self loadArrayData];

    [tableview reloadData];
}

The table populates great, adding is no problem, but when I try to delete a row, the app crashes on the following line:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {

    [someArray removeObjectAtIndex:indexPath.row];

    //update table etc..

If I use the debugger, I can see the array has some objects, and when I Log indexPath.row I get a value which is inside the array size.

I don't understand why it is crashing on this line... Who can help me?

The console outputs:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI removeObjectAtIndex:]: unrecognized selector sent to instance 0x6193890'

like image 672
CyberK Avatar asked Jun 25 '26 12:06

CyberK


2 Answers

I had a very similar problem and I was initiating my array with CoreData like this:

self.allContacts = (NSMutableArray*)[cdc.managedObjectContext executeFetchRequest:fetchRequest error:&error];

trying to cast the result from CoreDataController fetch request to NSMutableArray.

Turns out I need the function called "mutableCopy" at the end of fetch request.

self.allContacts = (NSMutableArray*)[[cdc.managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];

I don't think cast to (MutableArray *) is required but I have it just in case.

Hope this helps.

like image 111
C0D3 Avatar answered Jun 27 '26 02:06

C0D3


I had the same issue a week back. What I did was this:

Declared a NSMutableArray* globalArray as a global within the same tableViewController.m implementation file. Then inside

if (editingStyle == UITableViewCellEditingStyleDelete) {
   globalArray = [[NSMutableArray alloc] initWithArray:someArray];
   [globalArray removeObjectAtIndex:[indexPath row]]; 
}

And then I copied back this globalArray into someArray before the reloadData call. Works.

like image 33
Bourne Avatar answered Jun 27 '26 01:06

Bourne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!