I have an array of strings which i am already showing in my uitableview.
When edit is enabled for my uitableview, I am trying to move a string from say 4th row to 3rd row and i get EXC_BAD_ACCESS in the insert object at index part of my code when i debug this..
[myStringsArray insertObject:name atIndex:toIndexPath.row];
However if i do not debug and just build and run, i get to print the following line, and then it crashes without seeing EXC_BAD_ACCESS in my console.
NSLog(@"re-ordered myStringsArray array");
Here is my all code for the moveRowAtIndexPath method:
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *path = [documentsDirectoryPath stringByAppendingPathComponent:@"MyStrings.plist"];
//re-order array
NSString *name = [myStringsArray objectAtIndex:fromIndexPath.row];
[myStringsArray removeObjectAtIndex:fromIndexPath.row];
[myStringsArray insertObject:name atIndex:toIndexPath.row];
NSLog(@"re-ordered myStringsArray array");
if([myStringsArray writeToFile:path atomically: YES]){NSLog(@"write succesful");}
else {NSLog(@"write failed");}
[myTable reloadData];
}
Any ideas why it thinks that i'm trying to access something that's not there?
Correct me if I am wrong but my mutable array is already allocated and if the remove method worked, why wouldn't the insert method work?
Thank you
When you remove object from array it gets released so there's a good chance that its retain count goes to 0 and it gets deallocated. To avoid premature deallocation you can retain and release your object:
NSString *name = [[myStringsArray objectAtIndex:fromIndexPath.row] retain];
[myStringsArray removeObjectAtIndex:fromIndexPath.row];
[myStringsArray insertObject:name atIndex:toIndexPath.row];
[name release];
Or better use built-in NSMutableArray method for swapping objects you found yourself:
[myStringsArray exchangeObjectAtIndex:fromIndexPath.row withObjectAtIndex:toIndexPath.row];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With