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!
Related
I am working on an app that uses the following method to determine if a Core Data migration is needed:
- (BOOL)isMigrationNeeded {
BOOL isMigrationNeeded = NO;
NSError *error;
NSDictionary *sourceMetadata = [self sourceMetadata:&error];
if (sourceMetadata != nil) {
NSManagedObjectModel *destinationModel = [self managedObjectModel];
isMigrationNeeded = ![destinationModel isConfiguration:nil
compatibleWithStoreMetadata:sourceMetadata];
}
return isMigrationNeeded;
}
In the latest version of the database, an attribute was added that requires a mapping model to set its value. The value for the attribute is set properly, even though isConfiguration:compatibleWithStoreMetadata returns YES. As a result, the code which applies the mapping model is never called.
Is Core Data somehow applying the mapping model automatically?
This all works fine when the database is being migrated from the latest version. But I tested migration from an older version of the database and it failed to set the new attribute's value.
I wanted to try a recursive Core Data migration approach I found in a tutorial, but it will not do anything if isConfiguration:compatibleWithStoreMetadata returns YES.
I will gladly supply any necessary additional info.
There was a bug elsewhere in my code that overwrote the old version of the model with the new version of the model before isConfiguration:compatibleWithStoreMetadata was called.
So isConfig... correctly returned yes.
My Bad!!!
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'm new to Core Data and wondering if it is possible to get an object based on it's attributes, more specifically, an uniqueID I assigned to it. I'm trying to do this because I'm interfacing with a web server, which provides data that will updated the Core Data. I want to search through each of the web server objects, check the timestamp, and if it's different, retrieve that object from core data, and update. I've looked at using existingObjectWithId but it seems like I would have to know which object I'm searching for, or the ID of that object. I've also thought about sorting the data in both arrays, and then checking each simultaneously, but didn't think that is viable.
Here is what I'm doing so far:
-(NSMutableArray*) updateRootBeers:(NSMutableArray*)webRootBeerList{
NSManagedObjectContext* moc = [self managedObjectContext];
NSFetchRequest* fetchRequest = [[NSFetchRequest alloc]initWithEntityName:#"Rootbeer"];
coreDataRootBeerList = [[moc executeFetchRequest:fetchRequest error:nil]mutableCopy];
//check to see if core data has data, if not, call function to populate the list
if (coreDataRootBeerList.count <=0) {
[self addRootBeerToCoreData:webRootBeerList];
}else{
//otherwise I want to update the core data object if object data is different.
for(RootBeer* currentRootBeer in webRootBeerList){
RootBeer* mRootBeer = [moc existingObjectWithId:currentRootBeer error:nil];
}
}
}
I've also thought about using nested for loops to check for the data in each array, but that seems like poor coding.
Any help or thoughts would be great.
You want to make an NSFetchRequest. You can set the entity and provide a Predicate. Really simple and clean.
What is it?
I'm not sure I quite understand what this does.
- (NSString *)sectionIdentifier {
[self willAccessValueForKey:#"sectionIdentifier"];
NSString *tmp = [self primitiveSectionIdentifier];
[self didAccessValueForKey:#"sectionIdentifier"];
if (!tmp) {
tmp = #"bananas";
[self setPrimitiveSectionIdentifier:tmp];
}
return tmp;
}
How come I need this primitiveSectionIdentifier?
Ultimately, I'm using a example project from Apple's documentation to create a section identifier, to use with my NSFetchedResultsController.
While this does work. I am saying to myself that,
"sectionIdentifier" will be accessed,
then I'm setting "tmp" to primitiveSectionIdentifier. But primitiveSectionIdentifier has nothing there at this point!! Does it?
I then say I did access "sectionIdentifier". But I can't see how that happened between "Will" and "Did"!
Can someone help me understand this?
[self primitiveSectionIdentifier] is a so-called "primitive accessor" (see the Glossary of the Core Data Programming Guide). That is the function that actually fetches the value of the "sectionIdentifier" from the persistent store. The function is automatically created by the Core Data runtime.
willAccessValueForKey and didAccessValueForKey are "notification methods". According to the documentation, they are used for key-value observing, maintaining inverse relationships and so on.
So the pattern is:
Tell everybody that you are going to read a value.
Read the value.
Tell everybody that you have read the value.
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.