-[NSCFNumber count]: unrecognized selector - objective-c

I've got some Core Data code that follows Apple's sample code precisely (the Fetching Attribute Values that Satisfy a Given Function example). I'm using it to get the max value of a field, so I can then increment it when I insert the next object of that entity type.
I couldn't get the code to work at all, until I switched my Store Type from NSXMLStoreType to NSSQLiteStoreType, then all of a sudden everything seemed to be working. However, that's not the case. I noticed that it would always return the same value, even when I inserted objects with a higher one. But, after I quit and reopened (and thus the data was persisted and read back in), it would update with the new inserts.
So then I started committing and saving after each insert. After the first "autosave" though, I get the error below (twice in a row):
-[NSCFNumber count]: unrecognized selector sent to instance 0x100506a20
This occurs (two times in a rows) when I execute the fetch request once:
NSArray *objects = [context executeFetchRequest:request error:&error];
Update
I ran my code through the Zombies instrument, and was able to take a look at the object which is getting the error. The call that runs malloc to allocate it is: -[NSUserDefaults(NSUserDefaults) initWithUser:]. Since I don't have any of my own defaults set, I don't know what object this could be.
Update 2
I searched through all of my code for "release" and commented out every release or autorelease that the static analyzer didn't complain about. I still got the errors. I even went so far as to comment out every last release/autorelease in my code, and still got it. Now I'm fairly certain my own code isn't over-releasing.
Update 3
This post seems to be having the same problem, but his solution doesn't make sense. He changed the result type from NSDictionaryResultType to NSManagedObjectResultType, which produces an incorrect result. Instead of getting back a single value (the max that I'm looking for, that returns back every object of my entity class in the managed object context.
Here are the top-most levels of the stack trace (when I have it break on the exception, the first time):
#0 0x7fff802e00da in objc_exception_throw
#1 0x7fff837d6110 in -[NSObject(NSObject) doesNotRecognizeSelector:]
#2 0x7fff8374e91f in ___forwarding___
#3 0x7fff8374aa68 in __forwarding_prep_0___
#4 0x7fff801ef636 in +[_NSPredicateUtilities max:]
#5 0x7fff800d4a22 in -[NSFunctionExpression expressionValueWithObject:context:]
#6 0x7fff865f2e21 in -[NSMappedObjectStore executeFetchRequest:withContext:]
#7 0x7fff865f2580 in -[NSMappedObjectStore executeRequest:withContext:]
I've seen this question on numerous forums elsewhere on the web, but no one has offered a workable solution. By popular request, I added my own code below. To explain slightly, my entity's name is Box and the property I'm trying to get the value of is "sortOrder", an Int 32 attribute.
NSManagedObjectContext *context = [MyLibrary managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"Box"
inManagedObjectContext:context]];
// Specify that the request should return dictionaries.
[request setResultType:NSDictionaryResultType];
// Create an expression for the key path.
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:#"sortOrder"];
// Create an expression to represent the function you want to apply
NSExpression *expression = [NSExpression expressionForFunction:#"max:"
arguments:[NSArray arrayWithObject:keyPathExpression]];
// Create an expression description using the minExpression and returning a date.
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
// The name is the key that will be used in the dictionary for the return value.
[expressionDescription setName:#"maxSort"];
[expressionDescription setExpression:expression];
[expressionDescription setExpressionResultType:NSInteger32AttributeType];
// Set the request's properties to fetch just the property represented by the expressions.
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];
// Execute the fetch.
NSError *error;
NSNumber *requestedValue = nil;
NSArray *objects = [context executeFetchRequest:request error:&error];
NSLog( #"objects: %#", objects );
if (objects != nil && [objects count] > 0) {
requestedValue = [[objects objectAtIndex:0] valueForKey:#"maxSort"];
} else {
[[NSApplication sharedApplication] presentError:error];
}
[expressionDescription release];
[request release];
NSLog( #"Max Sort Order: %#", requestedValue );
return requestedValue;

Apparently this is a known bug, that occurs when using an NSInMemoryStoreType data store. It seems it works fine using an NSSQLiteStoreType.
You can find the OpenRadar entry here
I filled a duplicate for this bug — I encourage people that encounter the same issue to do the same, to increase the likelihood this annoying behaviour gets documented (or even better, fixed).

When you have memory management issues (selectors being sent to the wrong instances is a sign of memory management issues), there are a number of things you can do:
Re-read the Cocoa memory management rules and make sure that you're following them.
Run the static analyser. This will often pick up places where you have neglected the memory management rules.
Try using NSZombieEnabled to find out whether [and when] you are sending messages to unallocated instances.

-[NSCFNumber count]: unrecognized selector sent to instance 0x100506a20 means, that you are calling count on a NSCFNumber object, but NSCFNumber doesnt have this method. So most likely count is send to a deallocated NSArray or NSSet object.
USE NSZombieEnabled = YES. It might tell you, what happens. Search SO for informations on how to set it.

This can also happen if a binding is not set correctly. For example, if you bind a matrix boolean value to "Content" instead of (or in addition to) "Selected Tag" in IB you can get this error.
If all else fails, disconnect all of your bindings and reconnect them one at a time to see which one is the culprit.

After experiencing exactly the same problem with exactly the same sample code, it finally worked for me after I put [request release] in.

You are using the key path: sortOrder in your path expression. At least for XML-Databases Core-Data cannot handle case-sensitive types. Change your path to sortorder (all lower-case)
You will probably stumble over further problems if you are using controller classes.

Related

MagicalRecord not returning NSDictionary in fetch request

Here is my code:
NSPredicate *filter = [NSPredicate predicateWithFormat:#"aMostRecentFlag == 1"]; // find old records
NSFetchRequest *fetchRequest = [PreferenceData MR_requestAllWithPredicate: filter];
[fetchRequest setResultType: NSDictionaryResultType];
NSDictionary *preferenceData = [PreferenceData MR_executeFetchRequest:fetchRequest];
I get a warning from the build:
Incompatible pointer types initializing 'NSDictionary *' with an expression of type 'NSArray *'
which indicates MR is not returning the NSDictionary as documented; is there something wrong with my code? And by the way, nothing is returned by the fetch request, although there is a record that should have been.
It seems the comments have worked out the answer, but I am not sure that everyone is clear.
A fetch request returns an array of results. Usually, the objects representing the results will be the class specified in the model. If you are subclassing NSManagedObject (as you should be), it will be the subclass. If not, it will be a generic-looking NSManagedObject whose properties you access through valueForKey:.
However, you can ask for the results to be returned as dictionaries. This doesn't mean that executeFetchRequest:error: method returns a dictionary. Rather, it means that each object in the array will be a dictionary.
Whichever format you get the results in, you have to pull the object(s) you care about out of the array. A common idiom is to simply append .lastObject or .firstObject to the end of the executeFetchRequest:error: invocation. Something like:
MyObject *object = [context executeFetchRequest:request error:NULL].firstObject;
Magical Record is nothing more than a fancy wrapper around Core Data classes. It provides convenience methods, but all the usual semantics of Core Data still hold.

why do you make temporary objects, set them to variables, then release them?

I often see something like:
NSArray *tmpArr = [[NSArray alloc] initWithObjects:#"Info", nil];
self.userInfo = tmpArr;
[tmpArr release];
instead of:
self.userInfo = [[NSArray alloc] initWithObjects:#"Info", nil];
Does anyone know why the top code sample is more popular? Is it more correct memory management than the second?
Second code snippet causes a memory leak due to the array not being released. In most cases properties of object types (like NSArray in this case) are either retain or copy properties and this means they either increase the reference count of the assigned value or copy the whole object. Then the local variable can be (and should be) released if it's not needed anymore.
Non-leaking alternative to the second code snipped would be using autorelease:
self.userInfo = [[[NSArray alloc] initWithObjects:#"Info", nil] autorelease];
or simply:
self.userInfo = [NSArray arrayWithObjects:#"Info", nil];
Assuming that the property userInfo is marked retain, the second form will leak memory. [[NSArray alloc] initWithObjects] will create an array with a reference count of one. Assigning it to a retain property will increase the reference count to two and it will never come back down to zero and be released. It can be fixed either by using the first form you listed or by:
self.userInfo = [[[NSArray alloc] initWithObjects:#"Info", nil] autorelease];
so that the auto release will decrement the reference count to one at the next iteration of the run loop. From then when userInfo is cleared, the reference count will go down to zero and the array will be destroyed.
You should also take a look at this question
Apart from any other reasons there might be, it makes the code more readable and helps to prevent errors.
Your two examples are not equivalent, because you forgot to release the newly alloc/init'ed array in the second one. You would have needed
self.userInfo = [[[NSArray alloc] initWithObjects:#"Info", nil] autorelease];
here.
QED first reason ;-P
Moreover, when you create a local variable first, you can build up more complex objects before publicizing them via a property. If, for example, you were using a mutable array here and filled it with some more complex logic, assigning it to the property right away and only when going on filling it up, clients of your class might access the property with its contents being only half ready – a great provision for sporadic and hard to reproduce bugs.
So even though in your case it would not have been strictly necessary to use a local variable (if you either had autorelease'd it our used the new Automatic Reference Couting "ARC", which would have solved the leak issue automatically), in my opinion it is always a good idea to first get everything ready and then make it visible.
Clean code rules :)

Entity is not key value coding-compliant for the key

if (win) {
// Game was won, set completed in puzzle and time
// Calculate seconds taken
int timeTaken = (int)([NSDate timeIntervalSinceReferenceDate] - self.gameStartTime);
int bestTime = [[self.puzzle valueForKey:#"bestTime"] intValue];
if (timeTaken < bestTime && bestTime != 0) {
[self.puzzle setValue:[NSNumber numberWithInt:timeTaken] forKey:#"bestTime"];
NSLog(#"Best time for %# is %#", [self.puzzle valueForKey:#"name"], [self.puzzle valueForKey:#"bestTime"]);
}
}
This is some code from an iPad game I am making and I am using Core Data for storing the levels. When a level is completed and won, I want to set the best time for that level. The time taken is calculated, and if it is better than the previous best time, I want to set it as the best time for the level.
This code fails on the 'int bestTime' line when it tries to retrieve the best time from self.puzzle which is an NSManagedObject from Core Data. The best time is stored as an Integer 32 in the Core Data model. It fails with a SIGABRT error.
'[<NSManagedObject 0x95334d0> valueForUndefinedKey:]: the entity Puzzle is not key value coding-compliant for the key "bestTime".'
I have searched online for reasons as to why this is happening and how to fix it, but nothing seems to have helped. There are other places where I access Integer values from the Core Data model and they work perfectly, although they are used to filter and sort queries.
I also don't know if the line where I set the value will work.
Any help on this would be greatly appreciated.
EDIT: This is the code that fetches an array of puzzles of which one is taken to be the above puzzle.
// Define our table/entity to use
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Puzzle" inManagedObjectContext:managedObjectContext];
// Setup the fetch request
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
// Set the filter for just the difficulty we want
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"difficulty == %d", difficulty];
[request setPredicate:predicate];
// Define how we will sort the records
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"sortid" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[request setSortDescriptors:sortDescriptors];
[sortDescriptor release];
// Fetch the records and handle an error
NSError *error;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
Ok, Firstly, I would like to thank everyone who suggested ideas. They may not have helped me solve the problem, but I learnt more about Core Data and it is always good to find out what I should be checking when things don't work.
I don't really know what the problem was. Until this morning I had Xcode open for about 5 days I think and yesterday I added the attribute 'bestTime' to the data model. I can only assume that over the 5 days, Xcode had become a little unstable and thought it was saved when it wasn't. I had checked that I had saved the model attributes, in fact I must have checked 3 or 4 times as well as my habit of hitting Command+S after any change I make.
Anyway, I rebooted my machine earlier today and when I started up Xcode a few minutes ago I realised that 'bestTime' was not in the model file. I added it, reset the settings on the iPad simulator and it worked.
Thank you all again for the help, sorry the solution wasn't more interesting and code based. Although it makes me feel better that my code wasn't the cause.
That managed object doesn't have an attribute named “bestTime”. According to the exception message, it definitely is a Puzzle, so you haven't declared an attribute named bestTime in your model (or you misspelled it or capitalized it differently).
I did solve the same problem by delete and create the data model again and clean then rebuild again.
I think the bug is caused by core data does not update some data inside sometimes.
I don't think there's enough information here to determine the cause. You might try reading the Core Data Troubleshooting Guide; one possible cause could be if you initialized this particular instance of Puzzle using plain init rather than initWithEntity.
If you added attribute bestTime to the model at the later time, you might have forgotten to put declaration and implementation for them in the connected Managed Object Class.
Try convenience actions provided in Design -> Data Model -> Copy Objective-C ... Method Declarations/Implementations to Clipboard (when editing your Model file).
If parsing JSON into a managed object, be sure you're using the coreDataPropertyName property rather than the json-key-name key from JSON. Easy to mix up when they're named so similarly.
This error was driving me nuts, and all because I was using image-url rather than imageURL.

Debugging unexpected error message - possible memory management problem?

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:
Been deallocated and another variable has been allocated in the same place
Been clobbered by some bad code
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 marked retain, 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:
self.startingPlayers = [NSArray arrayWithObjects:#"first", #"second", nil];
and not like this:
startingPlayers = [NSArray arrayWithObjects:#"first", #"second", nil];
That one's bitten me countless times, including in the middle of a presentation right after I mentioned not to do it.
What does [self startingPlayers] return? Try printing that first:
NSLog("startingPlayers is %#", self.startingPlayers);
Perhaps startingPlayers contains a bad pointer (uninitialized) or a pointer to something that has already been released (and reused for something else).

iPhone's Core Data crashes on fetch request

I'm using the following code to grab a few objects from SQLite store (which is a prepared SQLite db file, generated with Core Data on desktop):
NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity: wordEntityDescription];
[request setPredicate: [NSPredicate predicateWithFormat: #"word = %#", searchText]];
NSError * error = [[NSError alloc] init];
NSArray * results = [[dao managedObjectContext] executeFetchRequest: request error: &error];
Eveyrthing seems to be setup properly, but executeFetchRequest:error: fails deeply inside Core Data (on NSSQLCore _newRowsForFetchPlan:selectedBy:withArgument) producing 256 error to the outside code.
The only kink I had setting up managedObjectContext is I had to specify NSIgnorePersistentStoreVersioningOption option to addPersistentStoreWithType as it was constantly producing 134100 error (and yes, I'm sure my models are just identical: I re-used the model from the project that produced the SQL file).
Any ideas?
P.S. Don't mind code style, it's just a scratch pad. And, of course, feel free to request any additional info. It would be really great if someone could help.
Update 1
Alex Reynolds, thanks for willingness to help :)
The code (hope that's what you wanted to see):
NSEntityDescription * wordEntityDescription; //that's the declaration (Captain Obviousity :)
wordEntityDescription = [NSEntityDescription entityForName: #"Word" inManagedObjectContext: ctx];
As for predicate – never mind. I was removing the predicate at all (to just grab all records) and this didn't make any differences.
Again, the same code works just fine in the desktop application, and that drives me crazy (of course, I would need to add some memory management stuff, but it at least should produce nearly the same behavior, shouldn't it?)
Can you add code to show how wordEntityDescription is defined?
Also, I think you want:
NSError *error = nil;
You may want to switch the equals symbol to like and use tick marks around the searchText field:
[request setPredicate: [NSPredicate predicateWithFormat: #"word like '%#'", searchText]];
NSPredicate objects are not put together like SQL, unfortunately. Check out Apple's NSPredicate programming guide for more info.