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.
Related
This should be easy, how difficult can it be.
I have a document based core data application with a very simple data model.
I have a "node" entity with a parent/children relationship to itself controlled by a NSTreeController, and viewed through an NSOutlineView. The "node" also has a non optional (to one) relationship to another entity type "nodeProperties" which is managed by a NSArrayController. I have NSManagedObject sublasses for both of the entities. My document class has outlets bound to both the tree controller and array controller instances.
My problem is how to ensure that, when a new "node" is created by a user interface action in the outline view, its relation to a suitable (pre-existing) nodeProperties object is populated.
Approaches I have tried / considered:
Let the tree controller create the "node" (from its add:, addChild: actions) and populate the relationship to a nodeProperties object in the "node" subclass awakeFromInsert method. The trouble is I cannot find a means of accessing any nodeProperties object from within the "node"s awakeFromInsert. The "appropriate" nodeProperties object is available from a method in the document class, but accessing the document object from the node awakeFromInsert method seems to break the principles of MVC, and I have read that the shared document object is not always safe in a drag and drop operation (which in my case also creates a new node object)
Write add: and addChild: action methods in the document class and invoke these from the end user actions instead of the tree controller (My drag and drop support is also in the document class). Then from within these methods invoke the add: and addChild: methods in the tree controller, then set the nodeProperties relationship on the newly created node. The trouble is I don't know how to ask the tree controller to give me a reference to the newly created node? I have tried using the selectedObjects method to get the parent, and then comparing the parents children before and after the add to get the new node. But the children content does not change at this time - perhaps it is a delayed update?
As a variant of 2, don't use the tree controller add:/addChild: methods at all, but instead create the node entity object in the document add:/addChild: methods using the tree controllers selectedOjects to get the parent. I don't really like this since it seems like doing something behind the tree controllers back, and I would have to setContent: each time I created root objects.
I have considered the possibility of observing the creation of the newly created node, but I don't know what to observe to achieve that.
Someone must have done something like this before - but I trawled to no avail. All help, advice, guidance would be very welcome.
OK so after much trawling and experimentation the answer was a variant of 3. The document creates the new node, populating its mandatory relationship, in add and addChild action methods, and then inserts the node into the tree controller using the method
NSTreeController insertObject:atArrangedObjectIndexPath:
For those interested, this is my addChild method in the document class. It has a few specifics from my data model
- (IBAction)addChildAction:(id)sender
{
NSArray *indexPaths = [nodeTreeController selectionIndexPaths];
NSArray *selectedObjects = [nodeTreeController selectedObjects];
for (NSUInteger i = 0; i < [indexPaths count]; i++)
{
QVXpandNode *parentNode = [selectedObjects objectAtIndex:i];
if ((parentNode) && ([parentNode.isMaster boolValue])) // can only add nodes under the master node
{
QVXpandNode *createdNode = [self createPopulatedNode];
// Dont belelieve below is safe when >1 selected,
// since adding a new node will result in the tree paths changing?
// Hmmm but I do want to support multiple selection addition??
[nodeTreeController
insertObject:createdNode
atArrangedObjectIndexPath:[[indexPaths
objectAtIndex:i] indexPathByAddingIndex:[parentNode.children count]]];
}
}
}
You will see that I am unsure whether I will put the second and later children at the right path if >1 rows were selected before calling the action.
The addSibling method is slightly more complicated by the need to calculate the last index path value, but is otherwise similar. I can reproduce it if anyone wants to see it, but the key to populating a mandatory relationship in a new tree node is to do it in the document class and then tell the tree controller precisely where in the tree you want to insert it.
I'm facing a strange issue where an NSFRC fetchedObjects array returning not all the objects it should. To give you some context, my application has several list view controllers, each of them having an NSFRC. I'm updating the list view within the delegate method controllerDidChangeContent. The problem I'm facing is the following: after storing an object in a background MOC and saving it, the controllerDidChangeContent is invoked but the object I just saved in the background thread doesn't show up in the NSFRC. Here is a piece of code that I'm using to check this:
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
NSManagedObjectContext *context = controller.managedObjectContext;
NSError *error = nil;
NSArray *array = [context executeFetchRequest:controller.fetchRequest error:&error];
if (nil != array) {
NSUInteger count = MIN(controller.fetchedObjects.count, array.count);
for (NSUInteger index=0; index<count; index++) {
NSManagedObject *a = array[index];
NSManagedObject *b = controller.fetchedObjects[index];
// Here you will see that sometimes the objects don't match
NSLog(#"%d: %# <--> %#", index, [[a body] text], [[b body] text]);
}
}
}
I'm expecting the NSFRC fetchedObjects array to be identical to the array returned by a manual executeFetchRequest (I'm using the NSFRC fetchRequest to manually fetch the data). However, this is not the case. The manual executeFetchRequest returns more object than the NSFRC fetchedObjects. Does anyone know what's going on? I've turned the caching on the NSFRC off but the same behavior is reported.
Thanks!
=== Update ====
Some update on that issue. I think there is a bug in Core Data because I was able to see some inconsistent results from the NSFRC and moreover was able to fix the problem by a workaround involving "touching" the object in question. Here is a scenario that explains what is happening:
Imagine the following Core Data model where:
- There are Cat objects and Master objects.
- A Cat can have one or more Master.
- A Master can have one or more Cat.
- A first NSFRC (let's call it NSFRC_A) is created to fetch all the cats with master named "Master_A". The predicate is { ANY master.name == "Master_A" }.
- A second NSFRC (let's call it NSFRC_B) is created to fetch all the cats with master named "Master_B". The predicate is { ANY master.name == "Master_B" }.
- There is a main managed object context that is used in the UI thread only
- There is a background managed object context created for each background thread, using the same persistent store as the main managed object context.
A cat named "Cat_A" is created in the background and assigned to master "Master_A". After the background context is saved, the main context is updated appropriately. At this point, the NSFRC_A notifies its delegate that a change has occurred and correctly reports "Cat_A".
Later on, in a background thread, the same cat "Cat_A" is assigned master "Master_B". After the background context is saved, the main context is updated appropriately. At this point, the NSFRC_A notifies its delegate of that change and correctly reports "Cat_A". NSFRC_B also notifies its delegate of that change but doesn't report "Cat_A" (it is missing from its fetchedObjects). However, if I manually perform a fetch using the same fetchRequest as NSFRC_B, I can see "Cat_A" being returned. The weird thing is that the "Cat_A" instance being returned is marked as a fault which explains why NSFRC_B doesn't return the "Cat_A" because it doesn't see it in memory.
This is a bug because I can fix that behavior by simply logging the "Cat_A" relationship to master when the changes from the background thread are merged into the main context: the logging basically touches the object and forces it to be realized into memory.
The problem appears to be a limitation of the NSFRC. According to this thread on the Apple Forum (https://devforums.apple.com/message/765374): "The limitation being that a fetched results controller for entity A won't always catch an update to entity B that would cause the predicate to change.". To solve the issue, I had to dirty the object I'm looking for before it is being merged into the main thread: then the NSFRC detects that change.
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.
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.
During the creation of a Core Data entity (Event), I am creating a relationship to another entity (Team). This relationship is many-to-one from Team to Events (one team, many events) and has an inverse relationship from Event to Team.
Team<----->>Event.
The delete rule for both relationships is set to 'Nullify'.
The below block of code works successfully on first population when a new Team is created during the creation of each Event. However, if I then remove an Event and attempt to re-add it, the existing Team is retrieved but the code fails when attempting to add the Team object to the Event in the final line of the example. The error is as follows: -[__NSCFDictionary managedObjectContext]: unrecognized selector sent to instance 0x699ed60
What is the correct way to create a relationship between the Event object to the Team object that already exists?
Team *currentTeam = self.team;
Team *newTeam = (Team *)[self loadTeamForNid:[NSNumber numberWithInteger: [teamNid integerValue]]];
// If the nid of the referenced team has changed,
if (![[[currentTeam nid] stringValue] isEqualToString:teamNid]) {
currentTeam = nil;
currentTeam = newTeam;
}
// If an event has not been set by this point, it does not exist in the CD store, and we need to create it.
if (currentTeam == nil) {
currentTeam = (Team *)[NSEntityDescription insertNewObjectForEntityForName:#"Team" inManagedObjectContext:[delegate managedObjectContext]];
[currentTeam populateTeamWithNode:[node nodeGet:teamNid]];
}
// TODO: This breaks on reload of an object
// self.team = currentTeam;
[self setValue:currentTeam forKey:#"team"];
Conceptually, you aren't mistaken: you set the event's "team" property to an instance of NSManagedObject that represents the appropriate team.
This message:
-[__NSCFDictionary managedObjectContext]: unrecognized selector sent to instance 0x699ed60
Means that some line of code is handling an instance of NSDictionary where it expects (I assume) an instance of NSManagedObject. When it tries to query the object's managedObjectContext, an exception is thrown, because an NSDictionary doesn't implement a method for that selector.
The first thing to do is put a breakpoint on that last line and see if currentTeam is actually an NSDictionary in disguise. (This seems unlikely, given the code above an exception would have been hit earlier.) If not, you'll have to hunt around for related properties that might be involved in this code path.
Note that Core Data supports a fetch request style where it returns NSDictionary instances instead of NSManagedObjects; if you are using this anywhere in your code, you might be accidentally passing the result along to another method that doesn't expect it.