UICollectionView sizeForItemAt IndexPath - swift

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.

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

Why app crashes with [NSObject(NSObject) doesNotRecognizeSelector:]?

The app sometimes crashes with [NSObject(NSObject) doesNotRecognizeSelector:], the selector being [UIImageView setImage:].
I captured it by setting an exception breakpoint and the crash happens when setting an UIImageView.image in prepareForReuse of a UICollectionViewCell:
class MyCell: UICollectionViewCell {
var coverImageView = UIImageView()
...
override func prepareForReuse() {
super.prepareForReuse()
coverImageView.image = nil
}
}
The prepareForReuse is called then the cell is instantiated:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "myReuseID", for: indexPath) as! MyCell
...
}
Why is that happening?
Also I cannot load the quick look data view for the UIImageView so maybe the object has been released?
The error messages in console are:
2017-01-21 15:56:19.653 MyApp[4873:20387361] -[__NSMallocBlock__ size]: unrecognized selector sent to instance 0x608000880aa0
2017-01-21 15:56:37.697 MyApp[4873:20387361] invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debug. This message will only appear once per execution.
2017-01-21 15:56:38.847 MyApp[4873:20617657] [Optimizely Logging]: Successfully saved data file to disk. Code revision is 229
2017-01-21 15:56:42.723 MyApp[4873:20387361] [Optimizely Logging]: (ERROR) NSInvalidArgumentException: Stack Trace:
(
0 CoreFoundation 0x000000010f587d4b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x000000010ef6121e objc_exception_throw + 48
2 CoreFoundation 0x000000010f5f7f04 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3 CoreFoundation 0x000000010f50d005 ___forwarding___ + 1013
4 CoreFoundation 0x000000010f50cb88 _CF_forwarding_prep_0 + 120
5 UIKit 0x000000010ba5e20f -[UIImageView _updateImageViewForOldImage:newImage:] + 297
6 UIKit 0x000000010ba59950 -[UIImageView setImage:] + 391
7 MyApp 0x000000010945e0d8 _TFC6MyApp23MyCell15prepareForReusefT_T_ + 136
8 MyApp 0x000000010945e112 _TToFC6MyApp23MyCell15prepareForReusefT_T_ + 34
9 UIKit 0x000000010c19aed1 -[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:viewCategory:] + 773
10 UIKit 0x000000010c19b8ea -[UICollectionView dequeueReusableCellWithReuseIdentifier:forIndexPath:] + 169
11 MyApp 0x00000001095bdee2 _TFC6MyApp23MyViewController14collectionViewfTCSo16UICollectionView13cellForItemAtV10Foundation9IndexPath_CSo20UICollectionViewCell + 594
12 MyApp 0x00000001095be747 _TToFC6MyApp23MyViewController14collectionViewfTCSo16UICollectionView13cellForItemAtV10Foundation9IndexPath_CSo20UICollectionViewCell + 87
13 UIKit 0x000000010c18675f -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:isFocused:notify:] + 467
14 UIKit 0x000000010c186586 -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:] + 35
15 UIKit 0x000000010c18ba5e -[UICollectionView _updateVisibleCellsNow:] + 4803
16 UIKit 0x000000010c191725 -[UICollectionView layoutSubviews] + 313
17 UIKit 0x000000010b90dab8 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1237
18 QuartzCore 0x000000010d558bf8 -[CALayer layoutSublayers] + 146
19 QuartzCore 0x000000010d54c440 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366
20 QuartzCore 0x000000010d54c2be _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
21 QuartzCore 0x000000010d4da318 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 280
22 QuartzCore 0x000000010d5073ff _ZN2CA11Transaction6commitEv + 475
23 QuartzCore 0x000000010d507d6f _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 113
24 CoreFoundation 0x000000010f52c267 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
25 CoreFoundation 0x000000010f52c1d7 __CFRunLoopDoObservers + 391
26 CoreFoundation 0x000000010f510f8e __CFRunLoopRun + 1198
27 CoreFoundation 0x000000010f510884 CFRunLoopRunSpecific + 420
28 GraphicsServices 0x0000000112b77a6f GSEventRunModal + 161
29 UIKit 0x000000010b848c68 UIApplicationMain + 159
30 MyApp 0x00000001092f5a7f main + 111
31 libdyld.dylib 0x00000001115b568d start + 1
)
2017-01-21 15:56:42.725 MyApp[4873:20387361] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSMallocBlock__ size]: unrecognized selector sent to instance 0x608000880aa0'
*** First throw call stack:
(
0 CoreFoundation 0x000000010f587d4b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x000000010ef6121e objc_exception_throw + 48
2 CoreFoundation 0x000000010f5f7f04 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3 CoreFoundation 0x000000010f50d005 ___forwarding___ + 1013
4 CoreFoundation 0x000000010f50cb88 _CF_forwarding_prep_0 + 120
5 UIKit 0x000000010ba5e20f -[UIImageView _updateImageViewForOldImage:newImage:] + 297
6 UIKit 0x000000010ba59950 -[UIImageView setImage:] + 391
7 MyApp 0x000000010945e0d8 _TFC6MyApp23MyCell15prepareForReusefT_T_ + 136
8 MyApp 0x000000010945e112 _TToFC6MyApp23MyCell15prepareForReusefT_T_ + 34
9 UIKit 0x000000010c19aed1 -[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:viewCategory:] + 773
10 UIKit 0x000000010c19b8ea -[UICollectionView dequeueReusableCellWithReuseIdentifier:forIndexPath:] + 169
11 MyApp 0x00000001095bdee2 _TFC6MyApp23MyViewController14collectionViewfTCSo16UICollectionView13cellForItemAtV10Foundation9IndexPath_CSo20UICollectionViewCell + 594
12 MyApp 0x00000001095be747 _TToFC6MyApp23MyViewController14collectionViewfTCSo16UICollectionView13cellForItemAtV10Foundation9IndexPath_CSo20UICollectionViewCell + 87
13 UIKit 0x000000010c18675f -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:isFocused:notify:] + 467
14 UIKit 0x000000010c186586 -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:] + 35
15 UIKit 0x000000010c18ba5e -[UICollectionView _updateVisibleCellsNow:] + 4803
16 UIKit 0x000000010c191725 -[UICollectionView layoutSubviews] + 313
17 UIKit 0x000000010b90dab8 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1237
18 QuartzCore 0x000000010d558bf8 -[CALayer layoutSublayers] + 146
19 QuartzCore 0x000000010d54c440 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366
20 QuartzCore 0x000000010d54c2be _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
21 QuartzCore 0x000000010d4da318 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 280
22 QuartzCore 0x000000010d5073ff _ZN2CA11Transaction6commitEv + 475
23 QuartzCore 0x000000010d507d6f _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 113
24 CoreFoundation 0x000000010f52c267 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
25 CoreFoundation 0x000000010f52c1d7 __CFRunLoopDoObservers + 391
26 CoreFoundation 0x000000010f510f8e __CFRunLoopRun + 1198
27 CoreFoundation 0x000000010f510884 CFRunLoopRunSpecific + 420
28 GraphicsServices 0x0000000112b77a6f GSEventRunModal + 161
29 UIKit 0x000000010b848c68 UIApplicationMain + 159
30 MyApp 0x00000001092f5a7f main + 111
31 libdyld.dylib 0x00000001115b568d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
I think the problem is that you are not calling the designated initializer of UIImageView, therefore its image property is not properly initialized and trying to assign to it crashes the app:
-[NSMallocBlock size]: unrecognized selector sent to instance 0x608000880aa0
The method tries to call the size method on the old image but the old image was set to some random memory address.
To fix it, initialize UIImageView properly using the designated initializer:
var coverImageView = UIImageView(image: nil)

Tableview controller error

Hi I am getting following error while running table view controller.
I am trying to diplay some harcoded text in UITableViewController.
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSSingleObjectArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
*** First throw call stack:
(
0 CoreFoundation 0x000000010e79134b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x000000010baab21e objc_exception_throw + 48
2 CoreFoundation 0x000000010e7e9bdf -[__NSSingleObjectArrayI objectAtIndex:] + 111
3 UIKit 0x000000010c738fe9 -[UITableViewDataSource tableView:heightForRowAtIndexPath:] + 181
4 UIKit 0x000000010c39c06b -[UITableViewController tableView:heightForRowAtIndexPath:] + 63
5 UIKit 0x000000010c0f1d7e -[UITableView _dataSourceHeightForRowAtIndexPath:] + 99
6 UIKit 0x000000010c32bac6 __66-[UISectionRowData refreshWithSection:tableView:tableViewRowData:]_block_invoke + 368
7 UIKit 0x000000010c32b081 -[UISectionRowData refreshWithSection:tableView:tableViewRowData:] + 3375
8 UIKit 0x000000010c330d31 -[UITableViewRowData rectForFooterInSection:heightCanBeGuessed:] + 501
9 UIKit 0x000000010c330e8f -[UITableViewRowData heightForTable] + 56
10 UIKit 0x000000010c0b2f36 -[UITableView _updateContentSize] + 381
11 UIKit 0x000000010c0db46f -[UITableView _rebuildGeometry] + 40
12 UIKit 0x000000010c0d96e3 -[UITableView setLayoutMargins:] + 282
13 UIKit 0x000000010c0d95a7 -[UITableView _setDefaultLayoutMargins:] + 103
14 UIKit 0x000000010c1127dc -[UIViewController _setContentOverlayInsets:] + 646
15 UIKit 0x000000010c112de2 -[UIViewController _updateContentOverlayInsetsFromParentIfNecessary] + 1000
16 UIKit 0x000000010c112859 -[UIViewController _updateContentOverlayInsetsForSelfAndChildren] + 101
17 UIKit 0x000000010c11e2d8 -[UIViewController _updateLayoutForStatusBarAndInterfaceOrientation] + 1027
18 UIKit 0x000000010c124002 -[UIViewController viewDidMoveToWindow:shouldAppearOrDisappear:] + 1238
19 UIKit 0x000000010c038620 -[UIView(Internal) _didMoveFromWindow:toWindow:] + 1590
20 UIKit 0x000000010c0500e2 -[UIScrollView _didMoveFromWindow:toWindow:] + 85
21 UIKit 0x000000010c02b6b4 __45-[UIView(Hierarchy) _postMovedFromSuperview:]_block_invoke + 151
22 UIKit 0x000000010c02b5a2 -[UIView(Hierarchy) _postMovedFromSuperview:] + 857
23 UIKit 0x000000010c03b2eb -[UIView(Internal) _addSubview:positioned:relativeTo:] + 1982
24 UIKit 0x000000010c0297a1 -[UIView(Hierarchy) addSubview:] + 838
25 UIKit 0x000000010bfe5f5b -[UIWindow addRootViewControllerViewIfPossible] + 849
26 UIKit 0x000000010bfe63a2 -[UIWindow _setHidden:forced:] + 293
27 UIKit 0x000000010bff9cb5 -[UIWindow makeKeyAndVisible] + 42
28 UIKit 0x000000010bf72c89 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 4818
29 UIKit 0x000000010bf78de9 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1731
30 UIKit 0x000000010bf75f69 -[UIApplication workspaceDidEndTransaction:] + 188
31 FrontBoardServices 0x000000011468a723 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24
32 FrontBoardServices 0x000000011468a59c -[FBSSerialQueue _performNext] + 189
33 FrontBoardServices 0x000000011468a925 -[FBSSerialQueue _performNextFromRunLoopSource] + 45
34 CoreFoundation 0x000000010e736311 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
35 CoreFoundation 0x000000010e71b59c __CFRunLoopDoSources0 + 556
36 CoreFoundation 0x000000010e71aa86 __CFRunLoopRun + 918
37 CoreFoundation 0x000000010e71a494 CFRunLoopRunSpecific + 420
38 UIKit 0x000000010bf747e6 -[UIApplication _run] + 434
39 UIKit 0x000000010bf7a964 UIApplicationMain + 159
40 swift_mvp 0x000000010b2dec2f main + 111
41 libdyld.dylib 0x000000010f6c468d start + 1
42 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
I am trying to run simple TableView controller
Code for table view controller is as follows:
import Foundation
import UIKit
class FeedsTableViewController: UITableViewController, UserView {
private var userPresenter: UserPresenter?
override func viewDidLoad() {
super.viewDidLoad()
userPresenter = UserPresenter(userView: self)
//userPresenter?.getUsers()
}
func startLoading() {
print("Loading started")
}
func stopLoading() {
print("Stop loading")
}
func onEmpty() {
print("No users available")
}
func onUsers(users: [User]) {
print("Users \(users.count)")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("number of section row fine")
return 10
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print("number Getting item")
let cellItem = tableView.dequeueReusableCell(withIdentifier: "USER_ITEM_ROW", for: indexPath)
//cellItem.textLabel?.text = "sdadas"
return cellItem
}
}

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.