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.
Related
I'm using NSFetchedResultsController to display a table of my NSManagedObject data.
Up to now, I've been using the name property on my objects to sort them:
NSFetchRequest* request = [[NSFetchRequest alloc] initWithEntityName:[Item entityName]];
NSSortDescriptor* nameSorter = [NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES selector:#selector(caseInsensitiveCompare:)];
request.sortDescriptors = #[nameSorter];
self.frc = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.moc
sectionNameKeyPath:#"nameInitial"
cacheName:nil];
Note that my sectionNameKeyPath is different from my sort request. As in this answer, I use a transient property on Item, called nameInitial. Its getter just reads name and returns the first letter.
So far so good. But now, I want to add a special condition: if the first word of the name is 'the', I don't want to sort by that. I want to sort by the first letter of the 2nd word. I can't do this with a transient property because now, the NSSortDescriptor on the fetch request will give a different order than the sectionNameKeyPath, which makes NSFetchedResultsController barf.
So I added a nameInitial field to Item and performed a lightweight migration. Now, I can add a NSSortDescriptor using this new attribute. I just have to populate it with the right letter. This is where my problem comes in: What do I do with the objects I already have in the DB, for which the nameInitial attribute is nil? As far as I can tell, these are my options:
Write a code that executes upon the first launch of the new version of the app, reads all the name fields and updates nameInitial appropriately.
Use awakeFromFetch to automatically update nameInitial for each object as it is loaded.
Override the getter of nameInitial, so it updates itself if it's nil.
I don't particularly like any of these options. The first one isn't elegant at all, and the last two mean either the awakeFromFetch or the getter will have unexpected side-effects. Is there a better way to do this that I'm missing?
You shouldn't do any of those. You should be writing a migration which processes this instead of using a lightweight (auto) migration (which can only fill the values in as nil).
Technically, your suggestions will work, but they aren't 'correct', will run slower and will be a maintenance burden in the future.
From your comment, the best option then is your first suggestion. You don't have many choices - use the built in migration processing or write your own version check and migration logic.
I have what I believe to be the simplest possible start to using Magical Record. I simply set up the stack and do a findAll call -- which I expect to return an empty array since this is a first run of the application. My code is below. For some reason, what I actually get is
executeFetchRequest:error: A fetch request must have an entity.
I can't for the life of me figure out why. I don't have versions of my data model, or anything really special. Just an entity and a generated NSMangedObject.. Has anyone seen this before?
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[MagicalRecord setupAutoMigratingCoreDataStack];
// Task *task = [Task MR_createEntity];
// task.title = #"Title";
NSArray *contexts = [Task MR_findAll];
NSLog(#"Initial load found %lu contexts", contexts.count);
}
Did you create and populate an NSManagedObjectModel using Xcode and the Core Data Entity Modeler? The error you're seeing happens when the entity isn't found in the model, or you don't have a model in the first place. Double check your entity name and class names as well. If you aren't using mogenerator, the you will need to make sure they match, or map them yourself using MR_entityName in your own entity's code.
Turns out the latest code in the main branch must have a bug.. I pulled the 2.2 branch instead, and it all started working.. Really odd, but there it is for anyone that stumbles on it.. Make sure you pull the latest stable!
I'm having the same problem as this question, but the answer of #davedelong is not working for me.
When following the Apple Example, for fetching the smallest date in a set of object I get the following error
-[NSDate count]: unrecognized selector sent to instance
My understanding is that NSExpression's max: only support NSArrays. So I need an other solution.
#davedelong suggested using an ascending NSSortDescriptor, and so I did :
NSFetchRequest* fetchRequest = [[NSFetchRequest alloc] init];
fetchRequest.entity = [NSEntityDescription entityForName:NSStringFromClass([GCSession class])
inManagedObjectContext:self.objectContext];
fetchRequest.fetchLimit = 1;
NSSortDescriptor* sort = [[NSSortDescriptor alloc] initWithKey:#"startDate" ascending:YES];
fetchRequest.sortDescriptors = [NSArray arrayWithObject:sort];
GCSession* session = [[self.objectContext executeFetchRequest:fetchRequest error:nil] lastObject];
return session.startDate;
The problem here is that the session object returned from the fetch doesn't seems to be the one with the smallest startDate. In my tests, it seems that it even returned the newest date but it doesn't seems consistent.
I could also fetch every GCSession object and sort them but that seems way overkill, especially that GCSession will be augmenting in number when the users will use the application.
Edit : A test project that demonstrate the bug in Apple's example code.
A sort only comes into play after you've fetch the objects. You've set a fetch limit of one and no predicates which tells the fetch "go grab any random single GCSession object". One the fetch has an array 1 element long, it then sorts it, which is useless.
If you want to use a sort to find a min or max, you have to fetch all the objects and then sort them. Removing the line:
fetchRequest.fetchLimit = 1;
… should allow the code to work.
However, you should be able to fetch min and max values with expressions. It's kind of a basic operation.
Edit: Look at the comments for more detail, but Apple's example can work if you change the backing store to SQL instead of XML
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.
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.