childContext and parentContext are both of "NSMainQueueConcurrencyType"
[childContext performBlock:^(void) {
[childContext save:NULL];
[parentContext performBlock:^(void) {
[parentContext save:NULL];
// Why is objectID for the inserted NSManagedObject still a temporary one here?
}];
}];
Question:
Is this the right way to save both the child and parent context
Why is it that after saving, the inserted NSManagedObject's objectID is still a temporary one?
I can think of a few rare occasions where you would want to have a main-queue MOC as a child of another main-queue MOC, but seeing that sure begs me to ask: What's the advantage of having both of them be NSMainQueueConcurrencyType?
Also, this is a known bug (at least it has been reported a number of times). When you insert and save from a child context, only the one directly connected to the persistent store gets its IDs mutated. So, when saving newly inserted items, you have several choices.
Acquire persistent IDs before saving.
Call [moc refreshObject:object mergeChanges:NO] and set all references to nil.
Acquire persistent IDs after the most parent saves
I prefer #3 because it requires a dip into the database. If you do it after, it can get them from the parent.
Related
I have a a main NSManagedObjectContext used in a few UIViewControllers to display the data (which is a UITableView with a list of Department)
3 entities one Department with a to-one to Boss with a to-many to Employee (In this case the employee have an NSData (which is an image) attribute with allow external storage).
Since I'm importing images in batches I'm doing it in a background thread which has its own NSManagedObjectContext.
The importing consists in creating the Boss entity and all the Employee and setting up the relationships.
Now my issue is :
if I use a child context of the main context for importing and save, then all the images stay in memory even though both context don't have changes.
if I use a context with no relation to the main context the image aren't staying in memory but the new data isn't showed in the UIViewController (obviously since the main context isn't notified of the changes done by the background context)
So I would like to still have the changes appear without having the images in memory (meaning I would like the Department to know that it has a Boss relationship but without having the images in memory). In short I would like them to be turned into fault as soon as the context is saved.
EDIT : I think the problem is when I save the child context, it merges with the main context and from there the newly inserted images stay in memory :/ and I have no idea how to release them (and no they're not auto released even with memory warning...)
EDIT 2 : I think I fixed it, here's what I did :
I used a child context tied to the main context and I listened to all the NSManagedObjectContextDidSaveNotification and for all the inserted updated I call refreshObject:mergeChanges: on it to turn it into fault.
I registered for all the notifications from every context.
-(void)contextDidSave:(NSNotification*)saveNotification {
NSManagedObjectContext *defaultContext = saveNotification.object;
NSArray *insertedObjects = [saveNotification.userInfo valueForKey:#"inserted"];
if (insertedObject) {
NSLog(#"INSERTED : %#", insertedObjects);
for (NSManagedObject *object in insertedObjects) {
[defaultContext refreshObject:object mergeChanges:NO];
}
}
NSArray *updatedObjects = [saveNotification.userInfo valueForKey:#"updated"];
if (insertedObject) {
NSLog(#"UPDATED : %#", updatedObjects);
for (NSManagedObject *object in updatedObjects) {
[defaultContext refreshObject:object mergeChanges:NO];
}
}
}
You can turn a specific object into a fault using refreshObject:mergeChanges:, passing NO for the mergeChanges argument.
Turning object into a fault (flag is NO) means that strong references to related managed objects (that is, those to which object has a reference) are broken, so you can also use this method to trim a portion of your object graph you want to constrain memory usage.
Documentation here.
Say that I perform a fetch of all entity Employee objects by doing: NSArray *employees = [context executeFetchRequest:request error:&error];
Then I set an instance variable in my class by doing: self.allEmployees = employees;
Then later in my app I will do some modifying to my employee objects but not through accessing self.allEmployees. I'm modifying them from another class.
Will my self.allEmployees array be updated to the changes I've made from another class to the employee objects? Or will my self.allEmployees array be in the state that the employee objects were when I first performed the fetch? (I'm suspecting the later)
The array you get back from the fetch request holds references to live managed objects. Unless you change a different fetchLimit or batchSize you get an array with as many fault objects as the query would return objects.
When you access a property of one of these fault objects CoreData retrieves the actual data for all the properties transparently and returns these to you.
A managed objects always has its own most recent value that was last called save on. So if you do a modification on the self.allEmployees you need to call save on the MOC and this will broadcast the changes to all other emoployee objects.
This is also the reason why KVO works on NSManagedObject properties, because they get notfified of all saved changes that affect them.
If you alter the objects you receive from the fetch, and don't copy them, then yes.
Those are all pointers.
So you shouldn't need to do another fetch request.
If you change values of an employee, the pointer won't change.
The only thing that changes is the instance variables, or properties.
I want a thorough list regarding comparison between the two. Things I have known:
executeFetchRequest:
Message sent to MOC
Return an array of managed objects
Goal: fetch objects from persistent store to MOC
With table view: has nothing to do with table view
Frequency: often used in a loop, so could be called many many times
performFetch:
Message sent to FRC
After calling it, use fetchedObjects to return an array of managed objects
With table view: FRC is specifically for keeping managed objects and table view rows in sync, and use performFetch to initialize that process.
Frequency: often only once. Unless fetch request of FRC changes, no need to call performFetch a second time
Please correct me if I am wrong and append the list. Thank you.
About executeFetchRequest:
Message sent to MOC
Yes
Return an array of managed objects
Yes, but you can also change the type of results you want to retrieve. In NSFetchRequest you can set a different result type with:
- (void)setResultType:(NSFetchRequestResultType)type
where NSFetchRequestResultType can be of different types. Taken from Apple doc:
enum {
NSManagedObjectResultType = 0x00,
NSManagedObjectIDResultType = 0x01,
NSDictionaryResultType = 0x02
NSCountResultType = 0x04
};
typedef NSUInteger NSFetchRequestResultType;
Goal: fetch objects from persistent store to MOC
Yes, creating a NSFetchRequest and performing a request, it the same as creating a SELECT statement in SQL. If you also use a NSPredicate it's the same as using SELECT-WHERE statement.
With table view: has nothing to do with table view
Yes, but with retrieved data you can populate a table
Frequency: often used in a loop, so could be called many many times
It depends, on what you want to achieve. It could be within a loop or not. Executing the request within a loop could have impact on performance but I would not be worried on that. Under the hood Core Data maintains a sort of cache mechanism. Every time you perform a request, if data are not in the cache, Core Data executes a round trip on your store (e.g. sql file) and populate the cache with the objects it has retrieved. If you perform the same query, the round trip will not performed again due to the cache mechanism. Anyway, you could avoid to execute a request within the run loop, simply moving that request outside the loop.
About performFetch:
Message sent to FRC
Yes
After calling it, use fetchedObjects to return an array of managed
objects
Yes, but you can also retrieve an object with [_fetchedResultsController objectAtIndexPath:indexPath]; if you are populating a specific cell within a table.
Here I really suggest to read a nice tutorial on NSFetchedResultsController
With table view: FRC is specifically for keeping managed objects and
table view rows in sync, and use performFetch to initialize that
process.
Yes, a NSFetchedResultsController works in combination with a NSManagedObjectContext for you. Furthermore, it enables lazy loading of data. Suppose you have 1000 elements you retrieve and you want to display them in a UITableView. Setting a request for a NSFetchRequest like:
[fetchRequest setFetchBatchSize:20];
and using it with an instance of a NSFetchedResultsController, it allows to load 20 elements at first. Then when you scroll, other 20 elements are loaded, and so on. Without a NSFetchedResultsController you must implement this behavior manually. Refer to the tutorial I provided for further info.
Frequency: often only once. Unless fetch request of FRC changes, no
need to call performFetch a second time
It depends on what you want to achieve. Most of the time you could call it once.
Hope that helps.
Edit
You have to call performFetch explicitly. I like to create a property for NSFetchedResultsController in my header file (.h) like
#property (nonatomic, strong, readonly) NSFetchedResultsController* fetchedResultsController;
and synthesize it in your implementation file (.m) like
#synthesize fetchedResultsController = _fetchedResultsController;
Then always within the .m file override the getter to create an new instance of it:
- (NSFetchedResultsController*)fetchedResultsController
{
// it already exists, so return it
if(_fetchedResultsController) return _fetchedResultsController;
// else create it and return
_fetchedResultsController = // alloc-init here with complete setup
return _fetchedResultsController;
}
Once done, within your class (for example in viewDidLoad method) use it like
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
// Handle the error appropriately.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}
You are comparing the wrong elements. NSFetchedResultsController uses the NSManagedObjectContext to perform the fetch, and under proper configuration, monitors the changes in the managed object context to verify the status of the fetch properties it is monitoring, but the actual fetches are done by the context. On both cases, NSManagedObjectContext does the fetch. The difference being that, using the NSManagedObjectContext directly, you get an NSArray type of object (the actual runtime class is different than an array you get using [NSArray array]), while NSFetchedResultsController has a different purpose (have a collection of results and monitor changes to the records and entity on its fetch request). In other words, NSFetchedResultsController works using the context, but it works different than just a simple collection of objects.
One observation: you shouldn't be using executeFetchRequest inside a loop, especially calling it "many many times". Each fetch has its performance cost. You can call executeFetchRequest once, and do a loop to check the result.
I have this code:
NSEntityDescription *userEntity = [[[engine managedObjectModel] entitiesByName] objectForKey:#"User"];
User *user = [[User alloc] initWithEntity:userEntity insertIntoManagedObjectContext:[engine managedObjectContext]];
and I want to know the id of the object inserted to the managed object context. How can i get that?
Will that id remain the same for that object's lifetime or will it persist to the sqlLite database beneath this and be something that can be used to uniquely identify it during a fetch operation (my ultimate goal).
Any help appreciated // :)
If you want to save an object's ID permanently you need to:
Save the object into the context so that the ID changes from a temporary to a permanent ID.
Extract the URI version of the permanent ID with -[NSManagedObjectID URIRepresentation]. That returns a NSURL you can store as transformable attribute in another managed object.
You can get the object by using -[NSPersistentStoreCoordinator managedObjectIDForURIRepresentation:] to generate a new NSManagedObjectID object and then use -[NSManagedObjectContext objectWithID:] to get the actual referenced managed object.
The URI is supposed to identify a particular object in a particular store on a particular computer but it can change if you make any structural changes to the store such as migrating it to a new model version.
However, you probably don't need to do any of this. ObjectIDs play a much smaller role in Core Data than they do in other Data Model systems. Core Data maintains an object graph that uniquely identifies objects by their location in the graph. Simply walking the graph relationships takes you to a specific unique object.
The only time you really need ObjectID is when you're accessing object across two or more persistent stores. You need them then because relationships don't cross stores.
Read up on "managed object IDs" in the Core Data Programming Guide
You can get the object id from the object with something like:
NSManagedObjectID *moID = [managedObject objectID];
First, you are constructing your objects in a non-preferred manner. Generally you should:
User *user = [NSEntityDescription insertEntityForName:#"User" intoManagedObjectContext:[engine managedObjectContext]];
Second, when you create the object it will get a temporary id which you can access via [user objectID] as David mentioned. Once you save the context then it will get a new "permanent" id.
However this id can and does change over the lifetime of the entity (although not the instance). Things like migrating the data can cause this id to change. However, between saving the context and exiting the application the id will remain the same.
I created a separate NSManagedObjectContext on a separate thread to perform some store maintenance. However, I have noticed that the context returns YES for hasChanges as soon as a managed object in it is even referenced e.g.
NSString *name = managedObject.name;
This context is created and used exclusively in 1 method. Why is it returning has changes, when there there are none?
That ks difficult to answer without seeing the code. Perhaps your object has a -awakeFromFetch call that touches a property or something else. Normally there should be no changes from just fetching an object unless you are doing something to that object either in the awakeFromFetch or somewhere else in your code.
update
Before the save, grab the deleted array, updated array and inserted array and take a peek at them. That will give you a hint as to what is going on.