I am trying to debug an application that is throwing up strange (to my untutored eyed) errors. When I try to simply log the count of an array…
NSLog(@"Array has %i items", [[self startingPlayers] count]);
…I sometimes get an error:
-[NSCFString count]: unrecognized selector sent to instance 0x1002af600
or other times
-[NSConcreteNotification count]: unrecognized selector sent to instance 0x1002af600
I am not sending ‘count’ to any NSString or NSNotification, and this line of code works fine normally.
A Theory…
Although the error varies, the crash happens at predictable times, immediately after I have run through some other code where I’m thinking I might have a memory management issue. Is it possible that the object reference is still pointing to something that is meant to be destroyed? Sorry if my terms are off, but perhaps it’s expecting the array at the address it calls ‘count’ on, but finds another previous object that shouldn’t still be there (eg an NSString)? Would this cause the problem?
If so, what is the most efficient way to debug and find out what is that address? Most of my debugging up until now involves inserting NSLogs, so this would be a good opportunity to learn how to use the debugger.
This is a sign that the memory location at which your code is expecting your array to live has either:
My bet would be on the first one. You’ll want to carefully look at where you are allocating the array and make sure that you’re not allowing its retain count to reach zero.
Remember that if you’re allocating the array using a convenience method (basically one that starts with
array) and not either retaining it or assigning it using dot notation (e.g.self.myArray = [NSArray arrayWith...]) and a property markedretain, it will be freed possibly as soon as the method in which you allocated it returns.TL;DR is to check where you’re assigning the array and make sure you’re using something like this:
and not like this:
That one’s bitten me countless times, including in the middle of a presentation right after I mentioned not to do it.