Can't delete row in section - iphone

i've got a problem by deleting cells in a section.The tableViewController has three sections with various cells. If I try to delete one cell, the debugger will show:
2015-01-23 20:22:15.105 Grade - Zensurenverwaltung[23854:5674475] * Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-3318.16.14/UITableView.m:1566
2015-01-23 20:22:15.133 Grade - Zensurenverwaltung[23854:5674475] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections. The number of sections contained in the table view after the update (3) must be equal to the number of sections contained in the table view before the update (3), plus or minus the number of sections inserted or deleted (0 inserted, 1 deleted).'
*** First throw call stack:
(
0 CoreFoundation 0x00000001008bef35 exceptionPreprocess + 165
1 libobjc.A.dylib 0x00000001025adbb7 objc_exception_throw + 45
2 CoreFoundation 0x00000001008bed9a +[NSException raise:format:arguments:] + 106
3 Foundation 0x0000000100d565df -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 195
4 UIKit 0x00000001013c98ff -[UITableView _endCellAnimationsWithContext:] + 10935
5 Grade - Zensurenverwaltung 0x00000001000fa0c2 _TFC26Grade___Zensurenverwaltung28TestTypesTableViewController9tableViewfS0_FTCSo11UITableView18commitEditingStyleOSC27UITableViewCellEditingStyle17forRowAtIndexPathCSo11NSIndexPath_T_ + 3618
6 Grade - Zensurenverwaltung 0x00000001000fa207 _TToFC26Grade___Zensurenverwaltung28TestTypesTableViewController9tableViewfS0_FTCSo11UITableView18commitEditingStyleOSC27UITableViewCellEditingStyle17forRowAtIndexPathCSo11NSIndexPath_T_ + 87
7 UIKit 0x00000001013edcb4 -[UITableView animateDeletionOfRowWithCell:] + 130
8 UIKit 0x00000001013ce125 __52-[UITableView _swipeActionButtonsForRowAtIndexPath:]_block_invoke + 72
9 UIKit 0x00000001012f68be -[UIApplication sendAction:to:from:forEvent:] + 75
10 UIKit 0x00000001013fd410 -[UIControl _sendActionsForEvents:withEvent:] + 467
11 UIKit 0x00000001013fc7df -[UIControl touchesEnded:withEvent:] + 522
12 UIKit 0x00000001016a3540 _UIGestureRecognizerUpdate + 9487
13 UIKit 0x000000010133bff6 -[UIWindow _sendGesturesForEvent:] + 1041
14 UIKit 0x000000010133cc23 -[UIWindow sendEvent:] + 667
15 UIKit 0x00000001013099b1 -[UIApplication sendEvent:] + 246
16 UIKit 0x0000000101316a7d _UIApplicationHandleEventFromQueueEvent + 17370
17 UIKit 0x00000001012f2103 _UIApplicationHandleEventQueue + 1961
18 CoreFoundation 0x00000001007f4551 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 17
19 CoreFoundation 0x00000001007ea41d __CFRunLoopDoSources0 + 269
20 CoreFoundation 0x00000001007e9a54 __CFRunLoopRun + 868
21 CoreFoundation 0x00000001007e9486 CFRunLoopRunSpecific + 470
22 GraphicsServices 0x00000001052fd9f0 GSEventRunModal + 161
23 UIKit 0x00000001012f5420 UIApplicationMain + 1282
24 Grade - Zensurenverwaltung 0x00000001001e164e top_level_code + 78
25 Grade - Zensurenverwaltung 0x00000001001e168a main + 42
26 libdyld.dylib 0x0000000102d87145 start + 1
27 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
And i just don't get it...
Here is my code:
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
var indexes: NSMutableIndexSet = NSMutableIndexSet()
dataTestType = context.executeFetchRequest(fetchRequestForTestType, error: nil) as [TestType]
if editingStyle == UITableViewCellEditingStyle.Delete {
context.deleteObject(dataTestType[indexPath.row] as NSManagedObject)
context.save(nil)
dataTestType.removeAtIndex(indexPath.row)
if dataTestType.count == 0 {
indexes.addIndex(indexPath.section)
}
tableView.beginUpdates()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
tableView.deleteSections(indexes, withRowAnimation: .Fade)
tableView.endUpdates()
}
}
Can anyone help me?
Thank You very much!

You remove an object at indexPath.row from the dataTestType array
dataTestType.removeAtIndex(indexPath.row)
And on the next line you try to get the object at the same index, but it won't exist if you deleted the only object in the array:
context.deleteObject(dataTestType[indexPath.row] as NSManagedObject)
You can simply solve the issue by reordering these two lines.
As matt pointed out, you can also use NSFetchedResultsController, as it is recommended for showing Core Data records in UITableView. Then you won't need dataTestType array at all. Now you call context.executeFetchRequest each time commitEditingStyle method is called. It is inefficient and can result in poor performance if you have many records to fetch.

Related

Swift Application crashes due to RLMException

I'm currently writing a programm which will be the final project in my major, "Computer Sciences". The application I'm making is written is Swift. It is basically an application which allows to write and classify the tasks that an user planned to do daily, monthly or yearly. I just got stuck in the debug console. I am unable to figure it out.
I asked to most of my classmates if they could help me out trying to understand from where the issue could from.
The issue might be from the searchBar functionality which is written through the following code:
extension CategoryViewController: SwipeTableViewCellDelegate {
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
guard orientation == .right else { return nil }
let deleteAction = SwipeAction(style: .destructive, title: "Delete") { action, indexPath in
// handle action by updating model with deletion
if let categoryForDeletion = self.categories?[indexPath.row] {
do {
try self.realm.write {
self.realm.delete(categoryForDeletion)
}
} catch {
print("Error deleting the category, \(error)")
}
}
}
// customize the action appearance
deleteAction.image = UIImage(named: "delete-icon")
return [deleteAction]
}
func collectionView(_ collectionView: UICollectionView, editActionsOptionsForItemAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> SwipeOptions {
var options = SwipeOptions()
options.expansionStyle = .destructive
return options
}
}
I got the issue:
'RLMException', reason: 'Index 2 is out of bounds (must be less than 2).'
*** First throw call stack:
(
0 CoreFoundation 0x000000010519e1bb __exceptionPreprocess + 331
1 libobjc.A.dylib 0x00000001038e6735 objc_exception_throw + 48
2 Realm 0x00000001028b4d3e _Z20RLMThrowResultsErrorP8NSString + 670
3 Realm 0x00000001028b5fa6 _ZL25translateRLMResultsErrorsIZ28-[RLMResults objectAtIndex:]E3$_6EDaOT_P8NSString + 118
4 Realm 0x00000001028b5ece -[RLMResults objectAtIndex:] + 110
5 RealmSwift 0x0000000101ef2e3c $S10RealmSwift7ResultsCyxSicig + 220
6 Todoey2 0x0000000101aea48f $S7Todoey222CategoryViewControllerC05tableC0_19editActionsForRowAt3forSay12SwipeCellKit0L6ActionCGSgSo07UITableC0C_10Foundation9IndexPathVAG0lG11OrientationOtFyAI_APtcfU_ + 303
7 Todoey2 0x0000000101aea8e2 $S7Todoey222CategoryViewControllerC05tableC0_19editActionsForRowAt3forSay12SwipeCellKit0L6ActionCGSgSo07UITableC0C_10Foundation9IndexPathVAG0lG11OrientationOtFyAI_APtcfU_TA + 18
8 SwipeCellKit 0x000000010224c3e8 $S12SwipeCellKit0A10ControllerC7perform6action4hideyAA0A6ActionC_SbtF + 776
9 SwipeCellKit 0x0000000102245d99 $S12SwipeCellKit0A10ControllerC7perform6actionyAA0A6ActionC_tF + 1241
10 SwipeCellKit 0x000000010224b734 $S12SwipeCellKit0A10ControllerC16swipeActionsView_9didSelectyAA0afG0C_AA0A6ActionCtF + 52
11 SwipeCellKit 0x000000010224e199 $S12SwipeCellKit0A10ControllerCAA0A19ActionsViewDelegateA2aDP05swipeeF0_9didSelectyAA0aeF0C_AA0A6ActionCtFTW + 9
12 SwipeCellKit 0x000000010222c40e $S12SwipeCellKit0A11ActionsViewC12actionTapped6buttonyAA0A12ActionButtonC_tF + 590
13 SwipeCellKit 0x000000010222c47c $S12SwipeCellKit0A11ActionsViewC12actionTapped6buttonyAA0A12ActionButtonC_tFTo + 60
14 UIKitCore 0x000000010d233ecb -[UIApplication sendAction:to:from:forEvent:] + 83
15 UIKitCore 0x000000010cc6f0bd -[UIControl sendAction:to:forEvent:] + 67
16 UIKitCore 0x000000010cc6f3da -[UIControl _sendActionsForEvents:withEvent:] + 450
17 UIKitCore 0x000000010cc6e31e -[UIControl touchesEnded:withEvent:] + 583
18 UIKitCore 0x000000010ce07018 _UIGestureEnvironmentSortAndSendDelayedTouches + 5387
19 UIKitCore 0x000000010ce00fd1 _UIGestureEnvironmentUpdate + 1506
20 UIKitCore 0x000000010ce009ad -[UIGestureEnvironment _deliverEvent:toGestureRecognizers:usingBlock:] + 478
21 UIKitCore 0x000000010ce0071d -[UIGestureEnvironment _updateForEvent:window:] + 200
22 UIKitCore 0x000000010d27078a -[UIWindow sendEvent:] + 4058
23 UIKitCore 0x000000010d24e394 -[UIApplication sendEvent:] + 352
24 UIKitCore 0x000000010d3235a9 __dispatchPreprocessedEventFromEventQueue + 3054
25 UIKitCore 0x000000010d3261cb __handleEventQueueInternal + 5948
26 CoreFoundation 0x0000000105103721 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
27 CoreFoundation 0x0000000105102f93 __CFRunLoopDoSources0 + 243
28 CoreFoundation 0x00000001050fd63f __CFRunLoopRun + 1263
29 CoreFoundation 0x00000001050fce11 CFRunLoopRunSpecific + 625
30 GraphicsServices 0x000000010a6731dd GSEventRunModal + 62
31 UIKitCore 0x000000010d23281d UIApplicationMain + 140
32 Todoey2 0x0000000101aef817 main + 71
33 libdyld.dylib 0x0000000104ce9575 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
This is an index out-of-bounds exception:
'RLMException', reason: 'Index 2 is out of bounds (must be less than
2).'
This happens when you subscript an array with an index that is greater or equal to the length of the array (equal to, because array indexes start at 0 not 1).
if let categoryForDeletion = self.categories?[indexPath.row]
The above line will crash if row >= self.categories.count. I would suggest looking into the numberOfRowsForSection function to figure out why you have more rows than categories.
Hard to tell whats going on with very little code.
I'd suggest littering your code with print statements (especially for your array counts, indexpath.row in cellForRow, editActionsForRowAt etc) and see where it's going wrong.
Looks like you are calling delete on a row that doesn't exist in your realm database, because of which it is crashing.
Here's how I'd update the closure
{ action, indexPath in
// handle action by updating model with deletion
print("\(indexPath.row)")
print("\(self.categories?.count)") //if these two mismatch, that's the problem
if let categoryForDeletion = self.categories?[indexPath.row] {
do {
try self.realm.write {
self.realm.delete(categoryForDeletion)
}
} catch {
print("Error deleting the category, \(error)")
}
}
}

Terminating app due to uncaught exception 'NSInvalidArgumentException', on deleting Row in UITableView [duplicate]

This question already has an answer here:
unrecognized selector sent to instance when no related entities found in Core Data
(1 answer)
Closed 4 years ago.
I am getting the above error when executing the following code:
func tableView(_ tableView: UITableView,
commit editingStyle: UITableViewCellEditingStyle,
forRowAt indexPath: IndexPath) {
let eventsOnArray = selectedRecipient?.events.allObjects // crashes here
guard let eventToRemove = eventsOnArray![indexPath.row] as? Event, editingStyle == .delete else {
return
}
managedContext.delete(eventToRemove)
do {
try managedContext.save()
getEvents()
self.eventList.reloadData()
} catch let error as NSError {
print("Saving error: \(error), description: \(error.userInfo)")
}
}
The detailed error is:
2018-03-11 12:20:49.732482-0400 Card Tracker[1516:29197] -[Recipient events]: unrecognized selector sent to instance 0x600000283840
2018-03-11 12:20:49.746477-0400 Card Tracker[1516:29197] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Recipient events]: unrecognized selector sent to instance 0x600000283840'
*** First throw call stack:
(
0 CoreFoundation 0x000000010fe2f12b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x000000010ef76f41 objc_exception_throw + 48
2 CoreFoundation 0x000000010feb0024 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3 CoreFoundation 0x000000010fdb1f78 ___forwarding___ + 1432
4 CoreFoundation 0x000000010fdb1958 _CF_forwarding_prep_0 + 120
5 Card Tracker 0x000000010e62b773 _T012Card_Tracker010ViewEventsC10ControllerC05tableC0ySo07UITableC0C_SC0gC16CellEditingStyleO6commit10Foundation9IndexPathV8forRowAttF + 195
6 Card Tracker 0x000000010e62c177 _T012Card_Tracker010ViewEventsC10ControllerC05tableC0ySo07UITableC0C_SC0gC16CellEditingStyleO6commit10Foundation9IndexPathV8forRowAttFTo + 119
7 UIKit 0x0000000110410a5f -[UITableView _animateDeletionOfRowAtIndexPath:] + 177
8 UIKit 0x0000000110419a59 __82-[UITableView _contextualActionForDeletingRowAtIndexPath:usingPresentationValues:]_block_invoke + 59
9 UIKit 0x0000000110953d67 -[UIContextualAction executeHandlerWithView:completionHandler:] + 174
10 UIKit 0x0000000110c41374 -[UISwipeOccurrence _performSwipeAction:inPullview:swipeInfo:] + 702
11 UIKit 0x0000000110c42bd1 -[UISwipeOccurrence swipeActionPullView:tappedAction:] + 112
12 UIKit 0x0000000110d25ed2 -[UISwipeActionPullView _tappedButton:] + 138
13 UIKit 0x00000001102ae972 -[UIApplication sendAction:to:from:forEvent:] + 83
14 UIKit 0x000000011042dc3c -[UIControl sendAction:to:forEvent:] + 67
15 UIKit 0x000000011042df59 -[UIControl _sendActionsForEvents:withEvent:] + 450
16 UIKit 0x000000011042ce86 -[UIControl touchesEnded:withEvent:] + 618
17 UIKit 0x000000011089ebad _UIGestureEnvironmentSortAndSendDelayedTouches + 5560
18 UIKit 0x0000000110898a4d _UIGestureEnvironmentUpdate + 1506
19 UIKit 0x000000011089841f -[UIGestureEnvironment _deliverEvent:toGestureRecognizers:usingBlock:] + 484
20 UIKit 0x00000001108974cb -[UIGestureEnvironment _updateGesturesForEvent:window:] + 288
21 UIKit 0x0000000110325f14 -[UIWindow sendEvent:] + 4102
22 UIKit 0x00000001102c9365 -[UIApplication sendEvent:] + 352
23 UIKit 0x000000012c2fe49d -[UIApplicationAccessibility sendEvent:] + 85
24 UIKit 0x0000000110c15a1d __dispatchPreprocessedEventFromEventQueue + 2809
25 UIKit 0x0000000110c18672 __handleEventQueueInternal + 5957
26 CoreFoundation 0x000000010fdd2101 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
27 CoreFoundation 0x000000010fe71f71 __CFRunLoopDoSource0 + 81
28 CoreFoundation 0x000000010fdb6a19 __CFRunLoopDoSources0 + 185
29 CoreFoundation 0x000000010fdb5fff __CFRunLoopRun + 1279
30 CoreFoundation 0x000000010fdb5889 CFRunLoopRunSpecific + 409
31 GraphicsServices 0x00000001159789c6 GSEventRunModal + 62
32 UIKit 0x00000001102ad5d6 UIApplicationMain + 159
33 Card Tracker 0x000000010e606727 main + 55
34 libdyld.dylib 0x000000011436dd81 start + 1
35 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
I am trying to delete a detail row in a Header-Detail based Entity. The crash occurs in the debugger as soon as I leave the line let eventsOnArray. I have placed a break point on that line, the code runs up until that point and then crashes when I use "Step Over".
getEvents:
func getEvents () {
// Now load all Events for this Receipient
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Event")
request.resultType = .dictionaryResultType
do {
events = try managedContext.fetch(request) as! [NSDictionary]
} catch {
print("Core Data Fetch Failed:", error.localizedDescription)
}
}
Core Data Definition:
Chances are that selectedRecepient is not an instance of Recipient class (or at least ObjC runtime thinks so).
Try to examine its type:
print(type(of: selectedRecipient))
If it prints NSManagedObject then you should make sure that Recipient entity has its class set to Recipient in data model editor – this tells Core Data to cast instances of that entity to the corresponding class.

CellForRowAtIndexPath crashing on curly braces

I am using a table view in my project, the crashlytics reports are showing a crash in my cellForRowAtIndexPath function on the curly braces exactly which is not helping me to find the bug. I am not being able to reproduce this bug either on my device nor on the simulators. The stack trace is below and the cellForRowAtIndexPath code is attached as an image.
Code
Crashlytics Stack-trace
Crashed: com.apple.main-thread
0 Synkers 0x104407d20 specialized HomeScreenViewController.tableView(UITableView, cellForRowAt : IndexPath) -> UITableViewCell (HomeScreenViewController.swift:208)
1 Synkers 0x104404134 #objc HomeScreenViewController.tableView(UITableView, cellForRowAt : IndexPath) -> UITableViewCell (HomeScreenViewController.swift)
2 UIKit 0x18a421474 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 668
3 UIKit 0x18a4219d8 -[UITableView _createPreparedCellForGlobalRow:willDisplay:] + 80
4 UIKit 0x18a401670 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2140
5 UIKit 0x18a1bcf10 -[UITableView layoutSubviews] + 140
6 UIKit 0x18a0e9000 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1256
7 QuartzCore 0x184cb90b4 -[CALayer layoutSublayers] + 184
8 QuartzCore 0x184cbd194 CA::Layer::layout_if_needed(CA::Transaction*) + 332
9 QuartzCore 0x184c2bf24 CA::Context::commit_transaction(CA::Transaction*) + 336
10 QuartzCore 0x184c52340 CA::Transaction::commit() + 540
11 UIKit 0x18a0de884 _afterCACommitHandler + 256
12 CoreFoundation 0x180c838b8 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32
13 CoreFoundation 0x180c81270 __CFRunLoopDoObservers + 412
14 CoreFoundation 0x180c8182c __CFRunLoopRun + 1292
15 CoreFoundation 0x180ba22d8 CFRunLoopRunSpecific + 436
16 GraphicsServices 0x182a33f84 GSEventRunModal + 100
17 UIKit 0x18a14f880 UIApplicationMain + 208
18 Synkers 0x104215ba4 main (main.m:14)
19 libdyld.dylib 0x1806c656c start + 4
This has nothing todo with the error, but since my reputation is too low, i'll have to write an answere:
Never force-uncast a cell!
...forIndexPath: indexPath) as! ...
This may cause errors and even crashes

Swift delete row with animation

Unfortunately, I have to ask this question again, because I have not found a solution yet.
At the moment I can delete it without animation, but now I want to delete it WITH animation.
My app get an error with this code:
/*************** TABLE VIEW DELETE LEBENSMITTEL ***************/
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == .Delete) {
let LM_ITEM = lebensmittel[indexPath.row]
managedObjectContext!.deleteObject(lebensmittel[indexPath.row])
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
self.DatenAbrufen()
}
}
2015-08-28 09:27:27.475 [32099:346567] *** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-3347.44.2/UITableView.m:1623
2015-08-28 09:27:27.483 [32099:346567] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (2) must be equal to the number of rows contained in that section before the update (2), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'
*** First throw call stack:
(
0 CoreFoundation 0x00000001091cdc65 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010b126bb7 objc_exception_throw + 45
2 CoreFoundation 0x00000001091cdaca +[NSException raise:format:arguments:] + 106
3 Foundation 0x00000001098ac98f -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 195
4 UIKit 0x0000000109f37c13 -[UITableView _endCellAnimationsWithContext:] + 12678
5 UIKit 0x0000000119d2937b -[UITableViewAccessibility deleteRowsAtIndexPaths:withRowAnimation:] + 48
6 App Name 0x00000001087ca640 _TFC12App_Name26AlteLebensmittelController9tableViewfS0_FTCSo11UITableView18commitEditingStyleOSC27UITableViewCellEditingStyle17forRowAtIndexPathCSo11NSIndexPath_T_ + 3360
7 App Name 0x00000001087ca887 _TToFC12App_Name26AlteLebensmittelController9tableViewfS0_FTCSo11UITableView18commitEditingStyleOSC27UITableViewCellEditingStyle17forRowAtIndexPathCSo11NSIndexPath_T_ + 87
8 UIKit 0x0000000109f5d1e6 -[UITableView animateDeletionOfRowWithCell:] + 132
9 UIKit 0x0000000109f3c3bd __52-[UITableView _swipeActionButtonsForRowAtIndexPath:]_block_invoke + 72
10 UIKit 0x0000000109e5bd62 -[UIApplication sendAction:to:from:forEvent:] + 75
11 UIKit 0x0000000109f6d50a -[UIControl _sendActionsForEvents:withEvent:] + 467
12 UIKit 0x0000000109f6c8d9 -[UIControl touchesEnded:withEvent:] + 522
13 UIKit 0x0000000109ea8958 -[UIWindow _sendTouchesForEvent:] + 735
14 UIKit 0x0000000109ea9282 -[UIWindow sendEvent:] + 682
15 UIKit 0x0000000109e6f541 -[UIApplication sendEvent:] + 246
16 UIKit 0x0000000109e7ccdc _UIApplicationHandleEventFromQueueEvent + 18265
17 UIKit 0x0000000109e5759c _UIApplicationHandleEventQueue + 2066
18 CoreFoundation 0x0000000109101431 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
19 CoreFoundation 0x00000001090f72fd __CFRunLoopDoSources0 + 269
20 CoreFoundation 0x00000001090f6934 __CFRunLoopRun + 868
21 CoreFoundation 0x00000001090f6366 CFRunLoopRunSpecific + 470
22 GraphicsServices 0x000000010de80a3e GSEventRunModal + 161
23 UIKit 0x0000000109e5a8c0 UIApplicationMain + 1282
24 App Name 0x00000001087ebb67 main + 135
25 libdyld.dylib 0x000000010b868145 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
The number of rows to show in your tableview is not the same you got in your datasource. Deleting a row with an animation take some time so when the deleting animation end try refreshing the tableview with yourTableview.reloadData() and remove the unused data from your datasource (before the refresh).
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return yourDataSource[section].count
}
Here an exemple in Objective-C:
- (void)removeRowAtIndex:(NSInteger)aIndex
{
//Set the row to remove from the tableView
NSMutableArray * tRemove = [NSMutableArray array];
NSIndexPath * tIndexPath = [NSIndexPath indexPathForRow:aIndex inSection:0];
[tRemove addObject:tIndexPath];
//Remove the deleted data from the datasource
NSMutableIndexSet * tRemoveIndexSet = [NSMutableIndexSet indexSet];
[tRemoveIndexSet addIndex:aIndex];
[YourDataSource removeObjectsAtIndexes:tRemoveIndexSet];
//Remove the row from tableView
[YourTableView deleteRowsAtIndexPaths:tRemove withRowAnimation:UITableViewRowAnimationLeft];
}
Swift version:
func removeRowAtIndex(aIndex:Int) {
//Set the row to remove from the tableView
var tRemove:Array<NSIndexPath> = Array()
let tIndexPath:NSIndexPath = NSIndexPath(forRow: aIndex, inSection: 0)
tRemove.append(tIndexPath)
//Remove the deleted data from the datasource
var tRemoveIndexSet:NSMutableIndexSet = NSMutableIndexSet()
tRemoveIndexSet.addIndex(aIndex)
YourDataSource.removeAtIndexes(tRemoveIndexSet)
//OR use removeAtIndex()
//YourDataSource.removeAtIndex(aIndex)
//Remove the row from tableView
YourTableView.deleteRowsAtIndexPaths(tRemove, withRowAnimation: .Left)
}
Add this extension if you want to use removeAtIndexes()
extension Array
{
mutating func removeAtIndexes(indexes: NSIndexSet) {
for var i = indexes.lastIndex; i != NSNotFound; i = indexes.indexLessThanIndex(i) {
self.removeAtIndex(i)
}
}
}
Source : removeObjectsAtIndexes for Swift arrays
Hope this can help you :)

iOS Application Terminates After Exception Thrown in UITableViewDataSource Method

Having meticulously followed the examples and instructions in the Table View Programming Guide for iOS about the proper order in which UITableView delegate and data source methods are called, I thought I had a good idea of how to implement the “handshake” shown in Figure 7-1 and the list that follows, but apparently not.
Here's the code I'm using…
- (void) tableView: (UITableView *) tableView commitEditingStyle: (UITableViewCellEditingStyle) editingStyle forRowAtIndexPath: (NSIndexPath *) indexPath {
NSLog(#"Removing %# row %d.", [dataModel objectAtIndex: indexPath.row], indexPath.row);
[tableView deleteRowsAtIndexPaths: [NSArray arrayWithObjects: indexPath, nil] withRowAnimation: UITableViewRowAnimationFade];
[dataModel removeObjectAtIndex: indexPath.row];
}
tableView is the UITableView
dataModel is an NSArray instance that holds the objects represented by the UITableViewCells from the tableView.
…and the error I'm getting…
2010-08-27 21:53:17.971 SportWatch[1299:307] *** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit/UIKit-1262.58/UITableView.m:920
2010-08-27 21:53:17.992 SportWatch[1299:307] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (4) must be equal to the number of rows contained in that section before the update (4), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted).'
*** Call stack at first throw:
(
0 CoreFoundation 0x35411ed3 __exceptionPreprocess + 114
1 libobjc.A.dylib 0x311f0811 objc_exception_throw + 24
2 CoreFoundation 0x35411d15 +[NSException raise:format:arguments:] + 68
3 Foundation 0x332b932f -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 62
4 UIKit 0x338dcda1 -[UITableView(_UITableViewPrivate) _endCellAnimationsWithContext:] + 4524
5 UIKit 0x338d586d -[UITableView _updateRowsAtIndexPaths:updateAction:withRowAnimation:] + 204
6 UIKit 0x338d5775 -[UITableView deleteRowsAtIndexPaths:withRowAnimation:] + 20
7 SportWatch 0x000060e7 -[MainViewController tableView:commitEditingStyle:forRowAtIndexPath:] + 670
8 UIKit 0x338d3c3f -[UITableView(UITableViewInternal) animateDeletionOfRowWithCell:] + 58
9 UIKit 0x33984071 -[UITableViewCell(UITableViewCellInternal) deleteConfirmationControlWasClicked:] + 28
10 CoreFoundation 0x353b9719 -[NSObject(NSObject) performSelector:withObject:withObject:] + 24
11 UIKit 0x33831d59 -[UIApplication sendAction:to:from:forEvent:] + 84
12 UIKit 0x33831cf9 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 32
13 UIKit 0x33831ccb -[UIControl sendAction:to:forEvent:] + 38
14 UIKit 0x33831a1d -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 356
15 UIKit 0x3383206b -[UIControl touchesEnded:withEvent:] + 342
16 UIKit 0x338309f5 -[UIWindow _sendTouchesForEvent:] + 368
17 UIKit 0x3383036f -[UIWindow sendEvent:] + 262
18 UIKit 0x3382ae13 -[UIApplication sendEvent:] + 298
19 UIKit 0x3382a74b _UIApplicationHandleEvent + 5110
20 GraphicsServices 0x3171a04b PurpleEventCallback + 666
21 CoreFoundation 0x353a6ce3 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 26
22 CoreFoundation 0x353a6ca7 __CFRunLoopDoSource1 + 166
23 CoreFoundation 0x3539956d __CFRunLoopRun + 520
24 CoreFoundation 0x35399277 CFRunLoopRunSpecific + 230
25 CoreFoundation 0x3539917f CFRunLoopRunInMode + 58
26 GraphicsServices 0x317195f3 GSEventRunModal + 114
27 GraphicsServices 0x3171969f GSEventRun + 62
28 UIKit 0x337d148b -[UIApplication _run] + 402
29 UIKit 0x337cf69f UIApplicationMain + 670
30 SportWatch 0x00002b23 main + 70
31 SportWatch 0x00002ad8 start + 40
)
terminate called after throwing an instance of 'NSException'
Program received signal: “SIGABRT”.
kill
Current language: auto; currently objective-c
quit
remove the object from the data set before deleting the row.