How can I debug 'unrecognized selector sent to instance' error - ios

I am creating a custom table cell view for my table view. After I connect an image view of custom cell (in storyboard) to my code in swift, I get the following error.
[UITableViewCellContentView image]: unrecognized selector sent to instance 0x7fb4fad7fd20'
*** First throw call stack:
(
0 CoreFoundation 0x000000010ccbb3f5 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010e7e9bb7 objc_exception_throw + 45
2 CoreFoundation 0x000000010ccc250d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x000000010cc1a7fc ___forwarding___ + 988
4 CoreFoundation 0x000000010cc1a398 _CF_forwarding_prep_0 + 120
5 UIKit 0x000000010d7d8881 -[UITableViewCell _marginWidth] + 151
6 UIKit 0x000000010d7ca23d -[UITableViewCell _separatorFrame] + 70
7 UIKit 0x000000010d7ca6fa -[UITableViewCell _updateSeparatorContent] + 360
8 UIKit 0x000000010d7d4e85 -[UITableViewCell _setSectionLocation:animated:forceBackgroundSetup:] + 1174
9 UIKit 0x000000010d634ea8 __53-[UITableView _configureCellForDisplay:forIndexPath:]_block_invoke + 1822
10 UIKit 0x000000010d5b5eae +[UIView(Animation) performWithoutAnimation:] + 65
11 UIKit 0x000000010d63477b -[UITableView _configureCellForDisplay:forIndexPath:] + 312
12 UIKit 0x000000010d63bcec -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 533
13 UIKit 0x000000010d61b7f1 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2846
14 UIKit 0x000000010d63165c -[UITableView layoutSubviews] + 213
15 UIKit 0x000000010d5be199 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 521
16 QuartzCore 0x00000001114b6f98 -[CALayer layoutSublayers] + 150
17 QuartzCore 0x00000001114abbbe _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
18 QuartzCore 0x00000001114aba2e _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
19 QuartzCore 0x0000000111419ade _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 242
20 QuartzCore 0x000000011141abea _ZN2CA11Transaction6commitEv + 390
21 QuartzCore 0x000000011141b255 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 89
22 CoreFoundation 0x000000010cbf0347 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
23 CoreFoundation 0x000000010cbf02a0 __CFRunLoopDoObservers + 368
24 CoreFoundation 0x000000010cbe60d3 __CFRunLoopRun + 1123
25 CoreFoundation 0x000000010cbe5a06 CFRunLoopRunSpecific + 470
26 GraphicsServices 0x0000000110daa9f0 GSEventRunModal + 161
27 UIKit 0x000000010d545550 UIApplicationMain + 1282
28 TestWork 0x000000010caa432e top_level_code + 78
29 TestWork 0x000000010caa436a main + 42
30 libdyld.dylib 0x000000010efc3145 start + 1
31 ??? 0x0000000000000001 0x0 + 1
)
Can you please tell me how to resolve this error?
Thank you.
I add an exception breakpoint in my project.
This is the line where it breaks.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as ItemTableViewCell <---------------
But I don't use 'image' in my code.

Try setting a symbolic breakpoint on -[NSObject(NSObject) doesNotRecognizeSelector:]. Just click [+] in the bottom left corner of the Breakpoint Navigator to add a breakpoint. Then click 'Add Symbolic Breakpoint'. Reproducing your crash now should give you a better idea where in your code the issue occurs.

You can easily track such crashes using Exception Breakpoints.
Open the Breakpoint Navigator and add the
Once you add the Exception Breakpoint, option will be open to choose the Exception.
Select Objective-C.
Run the code and crash the application, breakpoint will stop you to the point where the code is crashing.

The critical first step is to analyze the error message:
[UITableViewCellContentView image]: unrecognized selector sent to instance
This tells you that the "message" image was "sent" to an object of class UITableViewCellContentView. (In other words, an attempt was made to call the method image on an object of class UITableViewCellContentView.)
The first thing to ask is "Does this make any sense at all?" It may be that the named class has an Image method, but not an image method, and so the wrong method name was used on the call. Or it may be that the named method is someMethod:someParm:, but the class implements someMethod:someParm:anotherParm:, meaning that a parameter was omitted on the call.
Most often, though, the named class does not have any method even vaguely resembling the named method, meaning that somehow a pointer to the wrong object was used in the failing call.
For instance, one might do:
NSArray* myArray = [myDictionary objectForKey:#"values"];
NSString* myString = [myArray objectAtIndex:5];
And get an error along the lines of:
[__NSDictionaryI objectAtIndex:] unrecognized selector sent to instance
because the object retrieved from myDictionary was, in fact, an NSDictionary, not the NSArray that was expected.
Most confusing, unfortunately, is when this sort of error occurs deep in UI system code rather than in your own code. This can happen when you somehow passed the wrong object to a system interface, or perhaps configured the wrong class in Interface Builder or wherever.

Another possible reason is that the original object was destroyed and then another object was allocated at the same memory address. Then your code sends the message, thinking it still has a pointer to the old object, and Objective-C throws an exception because the new object doesn't understand that message.
To diagnose this problem, run the Profiler with 'Zombies' detection.

Swift 5.0
You can use Introspection to find out whether object responds to a particular selector or not..
let canWork = yourObject.respondsToSelector(Selector("image")) // true
Only if it is true that code will work.. otherwise it will crash for sure

In these scenarios I've found it helpful to look at two things
The call-stack
The local variables (and their types) at each stack frame
When I've had this error, it's usually because I sent a message to an instance of Type A, when I was expecting Type B.
In this specific scenario, you may not be satisfying a requirement of a parent class (given your instance of ItemTableViewCell most likely inherits).
Can you maybe show us the code for your ItemTableViewCell class?

You can use the following code to declare the variable:
let noteListTableViewCellobject = "NoteListTableViewCell";` `// Note listTablecell create custom cell`
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell:NoteListTableViewCell? = tableView.dequeueReusableCellWithIdentifier(noteListTableViewCellobject) as? NoteListTableViewCell
if (cell == nil) {
let nib:Array = NSBundle.mainBundle().loadNibNamed("NoteListTableViewCell", owner: self, options: nil)
cell = nib[0] as? NoteListTableViewCell
}
}

I had the same problem, and this worked for me:
Override the isEqual in your SKScene:
- (BOOL)isEqual:(id)other {
if (![other isMemberOfClass:[SKScene class]]) {
return false;
}
return [super isEqual:other];
}

You have to pass indexPath to declare object of tableview cell.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
return cell
}

Related

Wierd Crash on iphone app

i have a strange reaction with my app.
My app is working fine in almost 10 different devices and also has passed the tests and it's online. But one friend that has iPhone 5s with iOS 9.1 has an issue. When he tries to enter to a table view, which i append items to it with an API call with alamofire and swiftyjson.. the app crashes. From crashlytics i get this strange error
Crashed: com.apple.main-thread
0 Events Near Me 0x1000a532c specialized listMapViewController.tableView(UITableView, cellForRowAtIndexPath : NSIndexPath) -> UITableViewCell (listMapViewController.swift:196)
1 Events Near Me 0x1000a3c94 #objc listMapViewController.tableView(UITableView, cellForRowAtIndexPath : NSIndexPath) -> UITableViewCell (listMapViewController.swift)
2 UIKit 0x18a37220c -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 688
3 UIKit 0x18a372364 -[UITableView _createPreparedCellForGlobalRow:willDisplay:] + 80
4 UIKit 0x18a3617b8 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2440
5 UIKit 0x18a376f0c -[UITableView _performWithCachedTraitCollection:] + 104
6 UIKit 0x18a10f22c -[UITableView layoutSubviews] + 176
7 UIKit 0x18a01f7ac -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 644
8 QuartzCore 0x18981eb58 -[CALayer layoutSublayers] + 148
9 QuartzCore 0x189819764 CA::Layer::layout_if_needed(CA::Transaction*) + 292
10 QuartzCore 0x189819624 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 32
11 QuartzCore 0x189818cc0 CA::Context::commit_transaction(CA::Transaction*) + 252
12 QuartzCore 0x189818a08 CA::Transaction::commit() + 512
13 QuartzCore 0x1898120f8 CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 80
14 CoreFoundation 0x184a47bd0 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32
15 CoreFoundation 0x184a45974 __CFRunLoopDoObservers + 372
16 CoreFoundation 0x184a45da4 __CFRunLoopRun + 928
17 CoreFoundation 0x184974ca0 CFRunLoopRunSpecific + 384
18 GraphicsServices 0x18fbb0088 GSEventRunModal + 180
19 UIKit 0x18a08cffc UIApplicationMain + 204
20 Events Near Me 0x100095eec main (AppDelegate.swift:15)
21 libdyld.dylib 0x199da28b8 start + 4
And in the line 196 this is the code
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! locationEventsTableViewCell
var dict = arrRes[indexPath.row]
cell.eventTitle.text = dict["eventName"] as? String //here is the issue
So to explain you a bit, with this app you get some events near you depending on your location. I have a protection if there are no events there is a message. But we leave a couple of blocks away and i can get events, among with the cell.eventTitle... but my friend's iPhone crashes through it.
Any idea?
P.S. i'm now downloading iOS 9.1 to my simulator. Another friend with iPhone 5 doesnt have that issue.
As you say that other iphones doesn't have this problem I assumed that your friend's iphone maybe is overloaded from apps or anything else and it doesn't take the json variables in time!
So I suggest first to use if statements to avoid errors like this:
if dict["eventName"] as? String != nil {
cell.eventTitle.text = dict["eventName"] as? String
}
And if you want in your next update maybe you could use completions to reload your tableView data.
Hope it helps.

UICollectionViewController not working in upgraded XCode 7 project

I am working on a project that uses storyboards and was started in XCode 6 and has been upgraded to XCode 7. I am trying to add a UICollectionViewController. I get an exception on this line: let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! UnsplashCollectionViewCell
I have verified that the controller and cell are both assigned to my custom class in the storyboard, and that my reuse identifier is assigned to the cell and the same as the variable reuseIdentifier in my controller class.
About the only difference I can tell between a working UICollectionViewController and this project's is if I start a new project and add a UICollectionViewController I get the following in the Connections Inspector:
However, the Connections Inspector in my broken project looks like:
I'm not sure this is the problem, but I'm at a loss for what else it could be.
Crash log:
Uncaught exception: could not dequeue a view of kind: UICollectionElementKindCell with identifier UnsplashCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard
Full Crash Log:
2016-03-14 10:34:55.027 PixelSquidTouch[86881:2845927] [Crashlytics] Version 3.4.1 (92)
2016-03-14 10:34:55.063 PixelSquidTouch[86881:] App measurement v.1201000 started
2016-03-14 10:35:02.990 PixelSquidTouch[86881:2845927] *** Assertion failure in -[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:viewCategory:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3512.30.14/UICollectionView.m:3690
2016-03-14 10:35:03.013 PixelSquidTouch[86881:2845927] WARNING: GoogleAnalytics 3.14 void GAIUncaughtExceptionHandler(NSException *) (GAIUncaughtExceptionHandler.m:48): Uncaught exception: could not dequeue a view of kind: UICollectionElementKindCell with identifier UnsplashCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard
2016-03-14 10:35:08.054 PixelSquidTouch[86881:2845927] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'could not dequeue a view of kind: UICollectionElementKindCell with identifier UnsplashCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
*** First throw call stack:
(
0 CoreFoundation 0x000000010c95ce65 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010ffb0deb objc_exception_throw + 48
2 CoreFoundation 0x000000010c95ccca +[NSException raise:format:arguments:] + 106
3 Foundation 0x000000010fa274de -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 198
4 UIKit 0x000000010ddd04e9 -[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:viewCategory:] + 2009
5 UIKit 0x000000010ddd0945 -[UICollectionView dequeueReusableCellWithReuseIdentifier:forIndexPath:] + 169
6 PixelSquidTouch 0x000000010b8d9e6a _TFC15PixelSquidTouch32UnsplashCollectionViewController14collectionViewfS0_FTCSo16UICollectionView22cellForItemAtIndexPathCSo11NSIndexPath_CSo20UICollectionViewCell + 122
7 PixelSquidTouch 0x000000010b8d9f8f _TToFC15PixelSquidTouch32UnsplashCollectionViewController14collectionViewfS0_FTCSo16UICollectionView22cellForItemAtIndexPathCSo11NSIndexPath_CSo20UICollectionViewCell + 79
8 UIKit 0x000000010ddc05ba -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:isFocused:] + 483
9 UIKit 0x000000010ddc2ae0 -[UICollectionView _updateVisibleCellsNow:] + 4431
10 UIKit 0x000000010ddc723b -[UICollectionView layoutSubviews] + 247
11 UIKit 0x000000010d6224a3 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 703
12 QuartzCore 0x000000010f41759a -[CALayer layoutSublayers] + 146
13 QuartzCore 0x000000010f40be70 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366
14 QuartzCore 0x000000010f40bcee _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
15 QuartzCore 0x000000010f400475 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 277
16 QuartzCore 0x000000010f42dc0a _ZN2CA11Transaction6commitEv + 486
17 UIKit 0x000000010d596b47 _afterCACommitHandler + 174
18 CoreFoundation 0x000000010c888367 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
19 CoreFoundation 0x000000010c8882d7 __CFRunLoopDoObservers + 391
20 CoreFoundation 0x000000010c87df2b __CFRunLoopRun + 1147
21 CoreFoundation 0x000000010c87d828 CFRunLoopRunSpecific + 488
22 GraphicsServices 0x000000011197cad2 GSEventRunModal + 161
23 UIKit 0x000000010d56b610 UIApplicationMain + 171
24 PixelSquidTouch 0x000000010b957aad main + 109
25 libdyld.dylib 0x0000000110b5692d start + 1
26 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
So, you are trying to dequeue a cell but there is no cell with that ID. You need to open the cell in the storyboard or Xib and set the UICollectionElementKindCell ID to that id UnsplashCell
If you havent done the cell in the storyboard as a prototype cell, but are using a xib file, then you also need to register that cell with the tableview, so it knows about the cell type.
in your viewDidLoad:
let nibName = UINib(nibName: "UICollectionElementKindCell", bundle:nil)
self.tableView.registerNib(nibName, forCellReuseIdentifier: "UnsplashCell")
Update:
Look at the objects outlets etc. in the storyboard with the VC selected.
I am also struggling with this same issue since upgrading to XCode 7 last week. In our case, we were disabling user interaction whenever we displayed an activity view:
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
Then, in a callback block we were re-enabling user interaction with this:
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
Removing these calls resolved three out of four of these issues in our code; hopefully it can fix your issue as well. In any event, we haven't come up with a better approach as of yet.

Swift iOS - unwind segue crashing

I'm currently working on a section of my game where the user is taken to a second ViewController once they lose, this is my GameOverViewController.
I've successfully set up the second view controller with an interstitial advert that runs almost instantly once the GameOverViewController has loaded, the replay button is then only active once the interstitial advert has been closed.
My app crashes once the replay button has been pressed, it worked fine before I added the delay so I'm guessing it's something to do with my new code. The replay button is performing a unwind segue (or trying to), would anyone be able to help resolve?
class GameOverViewController: UIViewController {
#IBOutlet weak var button: UIButton!
}
override func viewDidLoad() {
super.viewDidLoad()
self.button.enabled = false
NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "enableButton", userInfo: nil, repeats: false)
//lots of code here to bring up google interstitial advert
}
func enableButton() {
self.button.enabled = true
}
The button is correctly greyed out for three seconds then turns blue, however once clicked the viewController hangs then crashes. The error brings up AppDelegate with the SIGABRT error. This is the extract from the output field...
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Ginger_Cat.GameOverViewController button:]: unrecognized selector sent to instance 0x7fe70739d120'
*** First throw call stack:
(
0 CoreFoundation 0x0000000111b4dc65 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x0000000113b96bb7 objc_exception_throw + 45
2 CoreFoundation 0x0000000111b550ad -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x0000000111aab13c ___forwarding___ + 988
4 CoreFoundation 0x0000000111aaacd8 _CF_forwarding_prep_0 + 120
5 UIKit 0x00000001128cbd62 -[UIApplication sendAction:to:from:forEvent:] + 75
6 UIKit 0x00000001129dd50a -[UIControl _sendActionsForEvents:withEvent:] + 467
7 UIKit 0x00000001129dc8d9 -[UIControl touchesEnded:withEvent:] + 522
8 UIKit 0x0000000112918958 -[UIWindow _sendTouchesForEvent:] + 735
9 UIKit 0x0000000112919282 -[UIWindow sendEvent:] + 682
10 UIKit 0x00000001128df541 -[UIApplication sendEvent:] + 246
11 UIKit 0x00000001128eccdc _UIApplicationHandleEventFromQueueEvent + 18265
12 UIKit 0x00000001128c759c _UIApplicationHandleEventQueue + 2066
13 CoreFoundation 0x0000000111a81431 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
14 CoreFoundation 0x0000000111a772fd __CFRunLoopDoSources0 + 269
15 CoreFoundation 0x0000000111a76934 __CFRunLoopRun + 868
16 CoreFoundation 0x0000000111a76366 CFRunLoopRunSpecific + 470
17 GraphicsServices 0x00000001151d0a3e GSEventRunModal + 161
18 UIKit 0x00000001128ca8c0 UIApplicationMain + 1282
19 Ginger Cat 0x000000010f9caa37 main + 135
20 libdyld.dylib 0x00000001142f0145 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
Here is the code in my GameViewController, there is currently no other code relating to the unwind in this ViewController
#IBAction func replay(segue: UIStoryboardSegue) {
}
Any help would be great, thanks.
The stack trace from the exception is telling you that you are calling the method button(_:) on your GameOverViewController, and that method does not exist (known as an "unrecognized selector" from Objective-C parlance).
It is not immediately clear where this is happening in your code, but I'm guessing that since you say the crash happens when you tap the button, there is an unintentional action called button(_:) connected to a touch event on your button in your storyboard. Select your button in the storyboard and choose the connections inspector on the right. Look for an action called button: - that could be the cause of the problem.
As a guess as to how this happened - did your replay(_:) unwind segue used to be called button(_:), and then you renamed it? Renamed methods in code aren't updated automatically in the storyboard, and can be a common source of bugs due to bad connections between the storyboard and code.
I think there is issue with you IBAction. Code below might be helpful.
#IBAction func replay(sender: UIButton) {
self.performSegueWithIdentifier("yourunwindidentifername", sender: self)
}

exception for app in release mode, not in debug mode

I'm having an exception in my didSelectRowAtIndexPath method and i'm not quite sure why. I'm showing the user a list of possibilities they can select from, the UITableView is populated based on values stored in Core Data. The currently selected item has a Checkmark indicator. My method is below:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let value = self.fetchedResultsController.objectAtIndexPath(indexPath) as CoreDataObject
currentSelected = value.id as Int
self.tableView.reloadData()
}
In development mode it's fine, but in production and testflight it crashes in this method. The crash log is below:
Crashed Thread 0 :
0 CoreFoundation 0x25f41a7d _CFRetain + 165
1 UIKit 0x29619d67 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 919
2 UIKit 0x296cb9df -[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 195
3 UIKit 0x2957da25 _applyBlockToCFArrayCopiedToStack + 309
4 UIKit 0x294f982b _afterCACommitHandler + 459
5 CoreFoundation 0x26007d95 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 21
6 CoreFoundation 0x26005453 __CFRunLoopDoObservers + 279
7 CoreFoundation 0x2600585b __CFRunLoopRun + 915
8 CoreFoundation 0x25f533c1 CFRunLoopRunSpecific + 477
9 CoreFoundation 0x25f531d3 CFRunLoopRunInMode + 107
10 GraphicsServices 0x2d3510a9 GSEventRunModal + 137
11 UIKit 0x29562fa1 UIApplicationMain + 1441
Is there anything i'm missing here? Why is this method crashing? I'm simply storing the currently selected ID and then reloading data so that it can show a checkmark after the reload. Is there something i'm missing here? It should be as simple as just getting the new id and then reloading the data.
The CoreDataObject that i'm using is from Objective-C and the id field is an NSNumber.
I tried other solutions below:
Crash when calling selectRowAtIndexPath:animated:scrollPosition:
iphone app crash at -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:]
iOS - didSelectRowAtIndexPath causes crash in app
In case anybody else has this issue. currentSelected was a global variable declared as Int and the value object has an id field thats `NSNumber. I changed it to the below and it works:
self.currentSelected = value.id.integerValue

-[__NSArrayI addObject:]: unrecognized selector sent to instance

I have this code:
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
var array: AnyObject = []
for obj in Category.allObjects() {
if var add = obj as? Category {
array.addObject(add.name)
println(add.name)
}
}
return String(array[section] as String)
}
Im using a Realm database and I am trying to get one of the columns of the database to print in the section headers. Im also using a the same process for all the other required UITableView methods eg/ numberOfSectionsInTable etc etc. The code is giving me this error:
2014-10-26 20:47:33.479 Project[14631:937721] -[__NSArrayI addObject:]: unrecognized selector sent to instance 0x7fdaf270ddb0
2014-10-26 20:47:33.481 Project[14631:937721] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI addObject:]: unrecognized selector sent to instance 0x7fdaf270ddb0'
*** First throw call stack:
(
0 CoreFoundation 0x0000000109960f35 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x00000001095f9bb7 objc_exception_throw + 45
2 CoreFoundation 0x000000010996804d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x00000001098c027c ___forwarding___ + 988
4 CoreFoundation 0x00000001098bfe18 _CF_forwarding_prep_0 + 120
5 BuildersUtility 0x0000000108d7f720 _TFC15BuildersUtility29ProductsDetailsViewController27numberOfSectionsInTableViewfS0_FCSo11UITableViewSi + 1408
6 BuildersUtility 0x0000000108d7f8ca _TToFC15BuildersUtility29ProductsDetailsViewController27numberOfSectionsInTableViewfS0_FCSo11UITableViewSi + 58
7 UIKit 0x000000010a478a7e -[UITableViewRowData _updateNumSections] + 84
8 UIKit 0x000000010a479474 -[UITableViewRowData invalidateAllSections] + 69
9 UIKit 0x000000010a2cdb03 -[UITableView _updateRowData] + 214
10 UIKit 0x000000010a2e300f -[UITableView numberOfSections] + 27
11 UIKit 0x000000010a4e0645 -[UITableViewController viewWillAppear:] + 97
12 UIKit 0x000000010a327821 -[UIViewController _setViewAppearState:isAnimating:] + 487
13 UIKit 0x000000010a352960 -[UINavigationController _startTransition:fromViewController:toViewController:] + 776
14 UIKit 0x000000010a353487 -[UINavigationController _startDeferredTransitionIfNeeded:] + 523
15 UIKit 0x000000010a353f47 -[UINavigationController __viewWillLayoutSubviews] + 43
16 UIKit 0x000000010a499509 -[UILayoutContainerView layoutSubviews] + 202
17 UIKit 0x000000010a277973 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 521
18 QuartzCore 0x000000010a089de8 -[CALayer layoutSublayers] + 150
19 QuartzCore 0x000000010a07ea0e _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
20 QuartzCore 0x000000010a07e87e _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
21 QuartzCore 0x0000000109fec63e _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 242
22 QuartzCore 0x0000000109fed74a _ZN2CA11Transaction6commitEv + 390
23 QuartzCore 0x0000000109feddb5 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 89
24 CoreFoundation 0x0000000109895dc7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
25 CoreFoundation 0x0000000109895d20 __CFRunLoopDoObservers + 368
26 CoreFoundation 0x000000010988bb53 __CFRunLoopRun + 1123
27 CoreFoundation 0x000000010988b486 CFRunLoopRunSpecific + 470
28 GraphicsServices 0x000000010dec79f0 GSEventRunModal + 161
29 UIKit 0x000000010a1fe420 UIApplicationMain + 1282
30 BuildersUtility 0x0000000108d9589e top_level_code + 78
31 BuildersUtility 0x0000000108d958da main + 42
32 libdyld.dylib 0x000000010baaf145 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
BTW if you have a better way for me to extract the code from the database for a project like this please chirp in! :)
Thanks in Advance
allObjects will return you an instance of RLMResults, which is one of the two list types in Realms, the other being RLMArray. They are both made to be similar to NSArrays or swift arrays, and implement a protocol called RLMCollection. Among other things, that means you can access its elements with normal [i] notation. So you can simply write
return Category.allObjects()[section].name
although you might want to do some checking before you return. Also, it is generally not advisable to repeat the allObjects() query more than you need to, so you could cache in a lazy instance variable or similar. In this case there probably aren't that many categories/section headers, so it shouldn't be an issue.
More importantly, keep in mind that although the RLMResults list you get back is ordered in the sense that it is an ordered list, there is no inherent order among the Category instances in the Realm, so the next time you do Category.allObjects() you are not really guaranteed to receive the objects in the same order. So what you should do is really to create an RLMArray of Category objects and make that a property of another object. Then the order will be preserved.
It is because AnyObject does not support the method addObject
I think what you have in mind is that you want the variable array to be an array of type AnyObject.
You should declare it this way:
var array:[AnyObject] = []
And then when you want to add anything to the array, do this:
array.append(add.name)
In addition to what #AnthonyKong is pointing out, it is a bit unclear from the above code why you would want an array of AnyObject in the first place.
var array = [AnyObject]()
It seems what you actually want is an array of String?
var array = [String]()
then your return statement is simplified down to:
return array[section]
When feeling up to it you might also look into filter to rip out some of that almost-boiler-plate-logic in your code.
I had a similar problem but with an NSMutableArray. Thanks to #Gusutafu's comment above that setting an array to #[] converts it to an NSArray.
My incorrect code (selectedTags is an NSMutableArray):
selectedTags = ([theInputParameters valueForKey:kAcronymTagsSelectedTags] != nil)
? [theInputParameters valueForKey:kAcronymTagsSelectedTags]
: #[];
This gave the error -[__NSArrayI addObject:]: unrecognized selector sent to instance when I tried to add an object.
My corrected code
selectedTags = ([theInputParameters valueForKey:kAcronymTagsSelectedTags] != nil)
? [theInputParameters valueForKey:kAcronymTagsSelectedTags]
: [NSMutableArray arrayWithArray:#[]];

Resources