Swift Application crashes due to RLMException - swift

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

Related

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.

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?

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

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.