I've got an application using Core Data (successfully) and I have an object graph that has a few root nodes that each have a to-many to tens of thousands of children. During my app's run, based on user input, I do the following (pseudocode):
Find the user selected root node,
Then fetch all its children, in ascending alphabetic order based on a property.
The trick here is that this data is constant. My Core Data store is read-only.
Doing this fetch is very time consuming. How can I pre-cache these results so that I completely avoid that fetch and store? The fetched results are used to fill a UITableView. When a user selects a cell of that tableview it drills down in to deeper data in the Core Data store - that data doesn't need to be precached..
If you are using NSFetchedResultsController with your tableview you can set a cacheName. You can set a batchSize in NSFetchRequest to bring the results in chunks. And also make sure you set the attribute your sorting on as an index in the core data model.
This code come from the Core Data Programming guide (chapter "Core Data Performance
") and shows how to make a prefetch.
NSManagedObjectContext *context = /* get the context */;
NSEntityDescription *employeeEntity = [NSEntityDescription
entityForName:#"Employee" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:employeeEntity];
[request setRelationshipKeyPathsForPrefetching:
[NSArray arrayWithObject:#"department"]];
Also use a limit on what is retruned from the real fetch. That will help performance.
Related
When I create a sqlite core data store in iCloud and seed on one device, it works fine and has around 6,000 records. When I create the store on the second device, it syncs, but only ends up with around 4,000 records (presumably from the transaction logs). My sync code in response to NSPersistentStoreDidImportUbiquitousContentChangesNotification reads...
NSUndoManager * undoManager = [context undoManager];
[undoManager disableUndoRegistration];
[context mergeChangesFromContextDidSaveNotification:info];
[context processPendingChanges];
[undoManager enableUndoRegistration];
However, when I insert a debug statement...
NSSet *updatedObjects = [[info userInfo] objectForKey:NSUpdatedObjectsKey];
NSSet *deletedObjects = [[info userInfo] objectForKey:NSDeletedObjectsKey];
NSSet *insertedObjects = [[info userInfo] objectForKey:NSInsertedObjectsKey];
NSLog(#"found transaction log. updated %d, deleted %d, inserted %d", updatedObjects.count, deletedObjects.count, insertedObjects.count);
I get an unexpected '0' for EVERYTHING, yet I know it's synching something because the database has around 4,000 records in it.
Does anyone have any advice on what might be going on here?
Thanks
Ray
If you have a look to the sqlite store itself, you will see that iOS is adding columns and tables to keep its reference. There's no way to add a primary key via code, unless you calculate it and store in a #property. But then again, core data doesn't care about it. Precalculated ID only serves you within your application logic.
For the iCloud part, you are right: iCloud transfer data by means of transaction log. The transaction log is copied to each device, and sqlite store get populated from there.
Documentation says that the transaction log is keep for a reasonable amount of time, then it is trashed. That could be the reason of only 4000 records instead of 6000.
Also, it is not your case, but beside that, in my experience, it is better to introduce iCloud since the beginning, when all devices are empty. If you introduce iCloud when device are partially filled with its own data, you could run into weird problems.
If you still haven't done that, I also suggest to turn on iCloud debugging in Xcode scheme.
My personal opinion, to synchronize more databases it is quite a difficult task, and I still wonder how it can be accomplished correctly by only dealing with transaction log sharing. Infact, at least with iOS 5 Core Data and iCloud was completely unreliable, and dangerous.
I have a list of uids, and I need to get Core Data objects with those uids:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"uid IN %#", uids];
[request setPredicate:predicate];
Now, I want to keep the objects in the same order as the listed uids. So if the array is [3, 1, 2], then I want the returned objects to be in that order as well.
Not setting an sort descriptor isn't an option with NSFetchedResultsController, so what should I set the sort descriptor to?
The sort descriptor can be set on a NSFetchRequest instance.
[request setSortDescriptors:descriptors];
where descriptors is an array of NSSortDescriptor instances.
A NSSortDescriptor can be created as follows:
NSSortDescriptor *sortDescriptorForKey = [[NSSortDescriptor alloc] initWithKey:#"someKey" ascending:YES]; // YES or NO based on your needs
About your question, what is the order of uids? Based on my experience (I haven't think on this until now) you cannot do what you are trying to achieve. Anyway, you could just replicate the descriptor for your uids in the NSFetchRequest.
Maybe someone could have some other ideas.
Objects in a persistent store are unordered. Typically you should impose order at the controller or view layer, based on an attribute such as creation date. If there is order inherent in your data, you need to explicitly model that.(https://developer.apple.com/library/mac/documentation/cocoa/conceptual/coredata/articles/cdFAQ.html)
So I do alot of fetching of my objects. At startup for instance I set an unread count for the badge on a tab. To get this unread count I need to fetch my datamodel objects to see which objects have the flag unread. So there we have a fetch. Then right after that method I do another fetch of all my datamodel objects to do something else. And then on the view controller I need to display my datamodel objects so I do another fetch there and so on.
So there are alot of calls like this : NSArray *dataModelObjects = [moc executeFetchRequest:request error:&error];
This seems kind of redundant to me? Since I will be working alot with my datamodel objects can I not just fetch them once in the application and access them through an instance variable whenever I need to access them? But I always want to have up-to-date data. So there can be added and/or deleted datamodel objects.
Am I making any sense on what I want to achieve here?
On of the concepts and benefits of Core Data is that you don't need to access the database every time you need an object - that's why NSManagedObjectContext was created - it stores those objects, retrieved from the database, so if you will try to get the object you've already get fromt the database, it wil be really fast.
And every change in those objects, made in the NSManagedObjectContext are automaticly brought to you.
But if you had some changes in the database, they may not be reflected in the NSManagedObjectContext, so you'll have to refresh them. You can read about keeping objects up-to-date here.
I work with iPhone iOS 4.3.
In my project I need a read-only, repopulated table of data (say a table with 20 rows and 20 fields).
This data has to be fetched by key on the row.
What is better approach? CoreData Archives, SQLite, or other? And how can I prepare and store this table?
Thank you.
I would use core data for that. Drawback: You have to write a program (Desktop or iOS) to populate the persistent store.
How to use a pre-populated store, you should have a look into the Recipes sample code at apple's.
The simplest approach would be to use an NSArray of NSDictionary objects and then save the array to disk as a plist. Include the plist in your build and then open it read only from the app bundle at runtime.
Each "row" would be the element index of the array which would return a dictionary object wherein each "column" would be a key-value pair.
I've done this 2 different ways:
Saved all my data as dictionaries in a plist, then deserialized everything and loaded it into the app during startup
Created a program during development that populates the Core Data db. Save that db to the app bundle, then copy the db during app startup into the Documents folder for use as the Persistent Store
Both options are relatively easy, and if your initial data requirements get very large, it's also proven to be the most performant for me.
Is there way to limit the number of saved objects in coredata like stack, where the last objects are automatically deleted?
No, that is something you would need to implement in code. You can, just before you call -save: on the NSManagedObjectContext query the NSManagedObjectContext for how many objects are going to be inserted and perform your custom logic at that point.