Swift delete row with animation - swift

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 :)

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)")
}
}
}

UICollectionView sizeForItemAt IndexPath

I'm trying to set size for my cell according to what's inside
this is my code and it crashes and I can't find an error messege.
extension TimelineCollectionVC: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "timeline", for: indexPath) as? Timeline
cell?.textView.translatesAutoresizingMaskIntoConstraints = true
cell?.textView.sizeToFit()
if cell?.containerView.subviews.count == 0 {
cell?.containerHeight.constant = 1
} else {
cell?.containerHeight.constant = (cell?.containerView.subviews.first?.frame.size.height) ?? 80
}
let cellHeight = (cell?.upperView.bounds.height)! + (cell?.textView.bounds.height)! + (cell?.containerView.bounds.height)! + (cell?.lowerView.bounds.height)!
return CGSize(width: 375, height: cellHeight)
}
}
reason: '-[NSCFString setSizeHasBeenSet:]: unrecognized selector sent to instance 0x610000076bc0'
*** First throw call stack:
(
0 CoreFoundation 0x0000000109dd9d4b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x00000001094d921e objc_exception_throw + 48
2 CoreFoundation 0x0000000109e49f04 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3 CoreFoundation 0x0000000109d5f005 ___forwarding_ + 1013
4 CoreFoundation 0x0000000109d5eb88 _CF_forwarding_prep_0 + 120
5 UIKit 0x00000001080d9485 -[UICollectionViewFlowLayout _getSizingInfosWithExistingSizingDictionary:] + 3691
6 UIKit 0x00000001080da97b -[UICollectionViewFlowLayout _fetchItemsInfoForRect:] + 127
7 UIKit 0x00000001080d3504 -[UICollectionViewFlowLayout prepareLayout] + 273
8 UIKit 0x00000001080f3d6c -[UICollectionViewData _prepareToLoadData] + 159
9 UIKit 0x00000001080f4618 -[UICollectionViewData validateLayoutInRect:] + 57
10 UIKit 0x000000010809b6d4 -[UICollectionView layoutSubviews] + 232
11 UIKit 0x0000000107817ab8 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1237
12 QuartzCore 0x0000000106fcdbf8 -[CALayer layoutSublayers] + 146
13 QuartzCore 0x0000000106fc1440 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366
14 QuartzCore 0x0000000106fc12be _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
15 QuartzCore 0x0000000106f4f318 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 280
16 QuartzCore 0x0000000106f7c3ff _ZN2CA11Transaction6commitEv + 475
17 QuartzCore 0x0000000106f7cd6f _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 113
18 CoreFoundation 0x0000000109d7e267 CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION + 23
19 CoreFoundation 0x0000000109d7e1d7 __CFRunLoopDoObservers + 391
20 CoreFoundation 0x0000000109d628a6 CFRunLoopRunSpecific + 454
21 UIKit 0x000000010774caea -[UIApplication _run] + 434
22 UIKit 0x0000000107752c68 UIApplicationMain + 159
23 Moden 0x0000000104ab4fbf main + 111
24 libdyld.dylib 0x000000010ad4e68d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
You should not be using dequeueReusableCell here. That is only for creating new cells. In this case you want to get an existing cell and should probably be using func cellForItem(at indexPath: IndexPath) -> UICollectionViewCell? in the UICollectionView class.

How to fix Error: this class is not key value coding-compliant for the key tableView.' [duplicate]

This question already has answers here:
this class is not key value coding-compliant for the key view [duplicate]
(7 answers)
Closed 6 years ago.
I made an app with Table View and Segmented Control, and this is my first time. I'm using some code and some tutorials, but It's not working. When I run my app It's crashing and it's showing this Error in logs:
MyApplication[4928:336085] * Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key tableView.'
* First throw call stack:
(
0 CoreFoundation 0x000000010516fd85 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x0000000105504deb objc_exception_throw + 48
2 CoreFoundation 0x000000010516f9c9 -[NSException raise] + 9
3 Foundation 0x000000010364e19b -[NSObject(NSKeyValueCoding) setValue:forKey:] + 288
4 UIKit 0x0000000103c37d0c -[UIViewController setValue:forKey:] + 88
5 UIKit 0x0000000103e6e7fb -[UIRuntimeOutletConnection connect] + 109
6 CoreFoundation 0x00000001050a9890 -[NSArray makeObjectsPerformSelector:] + 224
7 UIKit 0x0000000103e6d1de -[UINib instantiateWithOwner:options:] + 1864
8 UIKit 0x0000000103c3e8d6 -[UIViewController _loadViewFromNibNamed:bundle:] + 381
9 UIKit 0x0000000103c3f202 -[UIViewController loadView] + 178
10 UIKit 0x0000000103c3f560 -[UIViewController loadViewIfRequired] + 138
11 UIKit 0x0000000103c3fcd3 -[UIViewController view] + 27
12 UIKit 0x000000010440b024 -[_UIFullscreenPresentationController _setPresentedViewController:] + 87
13 UIKit 0x0000000103c0f5ca -[UIPresentationController initWithPresentedViewController:presentingViewController:] + 133
14 UIKit 0x0000000103c525bb -[UIViewController _presentViewController:withAnimationController:completion:] + 4002
15 UIKit 0x0000000103c5585c -[UIViewController _performCoordinatedPresentOrDismiss:animated:] + 489
16 UIKit 0x0000000103c5536b -[UIViewController presentViewController:animated:completion:] + 179
17 UIKit 0x00000001041feb8d __67-[UIStoryboardModalSegueTemplate newDefaultPerformHandlerForSegue:]_block_invoke + 243
18 UIKit 0x00000001041ec630 -[UIStoryboardSegueTemplate _performWithDestinationViewController:sender:] + 460
19 UIKit 0x00000001041ec433 -[UIStoryboardSegueTemplate _perform:] + 82
20 UIKit 0x00000001041ec6f7 -[UIStoryboardSegueTemplate perform:] + 156
21 UIKit 0x0000000103aa6a8d -[UIApplication sendAction:to:from:forEvent:] + 92
22 UIKit 0x0000000103c19e67 -[UIControl sendAction:to:forEvent:] + 67
23 UIKit 0x0000000103c1a143 -[UIControl _sendActionsForEvents:withEvent:] + 327
24 UIKit 0x0000000103c19263 -[UIControl touchesEnded:withEvent:] + 601
25 UIKit 0x0000000103b1999f -[UIWindow _sendTouchesForEvent:] + 835
26 UIKit 0x0000000103b1a6d4 -[UIWindow sendEvent:] + 865
27 UIKit 0x0000000103ac5dc6 -[UIApplication sendEvent:] + 263
28 UIKit 0x0000000103a9f553 _UIApplicationHandleEventQueue + 6660
29 CoreFoundation 0x0000000105095301 _CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION_ + 17
30 CoreFoundation 0x000000010508b22c __CFRunLoopDoSources0 + 556
31 CoreFoundation 0x000000010508a6e3 __CFRunLoopRun + 867
32 CoreFoundation 0x000000010508a0f8 CFRunLoopRunSpecific + 488
33 GraphicsServices 0x000000010726dad2 GSEventRunModal + 161
34 UIKit 0x0000000103aa4f09 UIApplicationMain + 171
35 Dhikr 0x0000000101f26282 main + 114
36 libdyld.dylib 0x00000001064c392d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
The code that I used is:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let foodList:[String] = ["Bread", "Meat", "Pizza", "Other"]
let drinkList:[String] = ["Water", "Soda", "Juice", "Other"]
#IBOutlet weak var mySegmentedControl: UISegmentedControl!
#IBOutlet weak var myTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var returnValue = 0
switch(mySegmentedControl.selectedSegmentIndex) {
case 0:
returnValue = foodList.count
break
case 1:
returnValue = drinkList.count
break
default:
break
}
return returnValue
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCellWithIdentifier("myCells", forIndexPath: indexPath)
switch(mySegmentedControl.selectedSegmentIndex) {
case 0:
myCell.textLabel!.text = foodList[indexPath.row]
break
case 1:
myCell.textLabel!.text = drinkList[indexPath.row]
break
default:
break
}
return myCell
}
#IBAction func segmentedControlActionChanged(sender: AnyObject) {
myTableView.reloadData()
}
Here is main.Storyboard
I checked the code many times, but it's not working. First I had to use only Table View, watching this tutorial (https://www.youtube.com/watch?v=ABVLSF3Vqdg) I thought it will work to use Segmented Control as in tutorial. But still doesn't work. Same code, same error.
Can someone help me ?
You have your storyboard set up to expect an outlet called tableView but the actual outlet name is myTableView.
If you delete the connection in the storyboard and reconnect to the right variable name, it should fix the problem.
Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?

Can't delete row in section

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.

crash on deleteRowsAtIndexPaths

My application crashes when I'm deleting row from table. Here is my sources where the bug is detected and stack trace. Thanx!
//delete row from database
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"\ncommitEditingStyle");
//delete user from Users table with specified ID
if(editingStyle == UITableViewCellEditingStyleDelete)
{
//Get the object to delete from the array.
[dbManager open: #DB_FILE_NAME];
//get userID from array usersIDList[row] = userID!
NSNumber *usersID = [usersIDList objectAtIndex: [indexPath row]];
[dbManager deleteUserWithID: [usersID intValue] table: #TABLE_USERS fieldName: #"UserID" ];
[dbManager close];
//Delete the object from the table.
[self.tableView deleteRowsAtIndexPaths:
[NSArray arrayWithObject: indexPath]
withRowAnimation: UITableViewRowAnimationFade];
}
}
- (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation
{
NSLog(#"\ndeleteRowsAtIndexPaths");
}
[Session started at 2010-11-15 18:01:23 +0200.]
2010-11-15 18:01:25.052 PhoneBook[12397:207] ******* Accessibility Status Changed: On
2010-11-15 18:01:25.101 PhoneBook[12397:207] ********** Loading AX for: com.yourcompany.PhoneBook ************
2010-11-15 18:01:30.060 PhoneBook[12397:207]
deleteBtnUserClick
2010-11-15 18:01:31.878 PhoneBook[12397:207]
commitEditingStyle
2010-11-15 18:01:31.881 PhoneBook[12397:207] *** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-1262.60.3/UITableView.m:920
2010-11-15 18:01:31.883 PhoneBook[12397:207] *** 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 (6) must be equal to the number of rows contained in that section before the update (6), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted).'
*** Call stack at first throw:
(
0 CoreFoundation 0x02510b99 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x0266040e objc_exception_throw + 47
2 CoreFoundation 0x024c9238 +[NSException raise:format:arguments:] + 136
3 Foundation 0x000b8e37 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 116
4 UIKit 0x00338d37 -[UITableView(_UITableViewPrivate) _endCellAnimationsWithContext:] + 8719
5 UIKit 0x00328511 -[UITableView deleteRowsAtIndexPaths:withRowAnimation:] + 56
6 UIKit 0x0aaca8fc -[UITableViewAccessibility(Accessibility) deleteRowsAtIndexPaths:withRowAnimation:] + 74
7 PhoneBook 0x00003491 -[RootViewController tableView:commitEditingStyle:forRowAtIndexPath:] + 392
8 UIKit 0x0032596d -[UITableView(UITableViewInternal) animateDeletionOfRowWithCell:] + 101
9 UIKit 0x0aacde92 -[UITableViewCellAccessibility(SafeCategory) deleteConfirmationControlWasClicked:] + 62
10 UIKit 0x002be7f8 -[UIApplication sendAction:to:from:forEvent:] + 119
11 UIKit 0x00349de0 -[UIControl sendAction:to:forEvent:] + 67
12 UIKit 0x0034c262 -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527
13 UIKit 0x0034ae0f -[UIControl touchesEnded:withEvent:] + 458
14 UIKit 0x002e23d0 -[UIWindow _sendTouchesForEvent:] + 567
15 UIKit 0x002c3cb4 -[UIApplication sendEvent:] + 447
16 UIKit 0x002c89bf _UIApplicationHandleEvent + 7672
17 GraphicsServices 0x02d6c822 PurpleEventCallback + 1550
18 CoreFoundation 0x024f1ff4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
19 CoreFoundation 0x02452807 __CFRunLoopDoSource1 + 215
20 CoreFoundation 0x0244fa93 __CFRunLoopRun + 979
21 CoreFoundation 0x0244f350 CFRunLoopRunSpecific + 208
22 CoreFoundation 0x0244f271 CFRunLoopRunInMode + 97
23 GraphicsServices 0x02d6b00c GSEventRunModal + 217
24 GraphicsServices 0x02d6b0d1 GSEventRun + 115
25 UIKit 0x002ccaf2 UIApplicationMain + 1160
26 PhoneBook 0x000026ec main + 102
27 PhoneBook 0x0000267d start + 53
)
terminate called after throwing an instance of 'NSException'
I've seen this before and it is definitely that you have forgotten to update source of data which fill up table. But that part of code is missing.
The method which caused this is
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return ;
}
Yes, the problem was in method numberOfRowsInSection
So, to leave troubles you should:
In function commitEditingStyle delete data from your array, database etc.
Decrement your current row count.
[tableView beginUpdates];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject: indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView endUpdates];
And all be OK!
Updated Swift 4.2
If you are about to remove last row in section, you should remove entire section instead of row. To do that:
tableView.beginUpdates()
dataArray.remove(at: row)
if tableView.numberOfRows(inSection: section) == 1 {
tableView.deleteSections(IndexSet(integer: section), with: .automatic)
}
else {
tableView.deleteRows(at: indexPath, with: .fade)
}
tableView.endUpdates()
Pretty clear from the error message:
'Invalid update: invalid number of
rows in section 0. The number of rows
contained in an existing section after
the update (6) must be equal to the
number of rows contained in that
section before the update (6), plus or
minus the number of rows inserted or
deleted from that section (0 inserted,
1 deleted).'
The object you are trying to delete doesn't get deleted in your datasource.
If I assume that your UITableViewDataSource uses dbManager too, you have to fix dbManager to actually delete the object.
I got the same error and reason was I delete the last row in the table and
my numberOfSectionsInTableView implementation return rowsArray count which was 0..
changing to minimum of 1 solve the case