RestKit 0.10.3 Save Issues - restkit

I've recently inherited an Xcode project making use of RestKit and have upgraded it to 0.10.3 to get it working under iOS6.
The JSON response object mapping appears to all be ok although I have an issue where certain child collections are not actually saved.
For example I have
syncResponse.newEntities.customers
and then each customer has an array of addresses.
I save after the didLoadObjects with the following call:
NSError* err = nil;
[[[RKObjectManager sharedManager] objectStore] save:&err];
I've found that this will only save the Customer and none of the Address data or any child collections. When I navigate to the Customer view the address area is empty.
However if I add the following block of code before the save lines then a list of suburbs prints out in xCode output and the addresses are persisted and all is fine.
for (Customer* customer in syncResponse.newEntities.customers)
{
for (Address *address in [customer address]) {
NSLog(#"%#", address.suburb);
}
}
Is there any reason why this should be happening or should a different save method be called?
Any help would be most appreciated!

Related

Initialize a document and mark it as "unchanged"

I'm trying to write my first Core Data driven document-oriented OSX application in Swift, as I want to get a bit more into Mac programming. The documents should be saved as XML files only, which I've managed to successfully configure.
The problem is that I want to pre-add some information to the document upon initializing without really "modifying" the document. The information is just required and should be in the document, but if the user creates and right away closes a document he should not be asked to save.
I've defined my Core Data data model and I've created NSManagedObject subclasses from my model. In my document's init method I'm doing this:
override init() {
super.init()
// Add your subclass-specific initialization here.
let newItem = NSEntityDescription.insertNewObjectForEntityForName("MyItem", inManagedObjectContext: self.managedObjectContext) as! MyItem;
newItem.descriptionText = "Item number 1";
newItem.itemNumber = 1;
}
This does add a new item to my document and when I save and re-load I can verify that the item is there. However, doing it this way, the document is marked "dirty" and upon closing it, the user is asked to save the changes.
How would I perform an initialization of my data model without actually marking the document as edited?
For those interested, I managed to solve this to work in my case. First of all, I moved my intialization code to
convenience init?(type typeName: String, error outError: NSErrorPointer)
Then I temporarily suspend the undo-functionality:
self.managedObjectContext.processPendingChanges();
self.undoManager.disableUndoRegistration();
After I make my changes I re-enable the undo-functionality:
self.managedObjectContext.processPendingChanges();
self.undoManager.enableUndoRegistration();
This has worked well so far.

Archiving Core Data entity with a relationship

I want to be able to support copy and paste for a tableview row showing a core data entity. This entity has one attribute and two relationships. When I use the dictionary archiving technique recommended by Apple (from 'NSPersistentDocument Core Data Tutorial') I find that the relationships throw an error. Here's the essential piece of code where the problem occurs:
for (id sectionObject in selectedSectionsArray){
NSDictionary *thisDictionary = [sectionObject dictionaryRepresentation]; // 'sectionObject' has 1 attribute and 2 relationships (one-to-many)
[copyObjectsArray addObject:[sectionObject dictionaryRepresentation]];
}
NSPasteboard *generalPasteboard = [NSPasteboard generalPasteboard];
[generalPasteboard declareTypes:[NSArray arrayWithObjects:MSSectionsPBoardType, NSStringPboardType, nil] owner:self];
NSData *copyData = [NSKeyedArchiver archivedDataWithRootObject:copyObjectsArray]; // Here's where it crashes. ERROR MESSAGE: "-[NSManagedObject encodeWithCoder:] unrecognized selector sent to instance 0x22fd410"
Therefore, it seems the only way to copy a relationship to the pasteboard must be to archive its URI. In that case, I have to deal with the headache of referencing temporary ID's. Could someone please confirm that this is the case? Does it have to be so hard?
You haven't read that document closely enough. In the section Custom Employee Logic, it explains that relationships will not be copied for several reasons described there. It then explains how the code handles copying only specific attributes. It seems like you followed the document as far as choosing specific attributes to copy but not about leaving out relationships.
As for the error you're seeing,
-[NSManagedObject encodeWithCoder:] unrecognized selector sent to instance 0x22fd410
This happens because you're calling archivedDataWithRootObject: on a dictionary that contains objects that don't conform to NSCoding, specifically, your managed objects. Archiving like this only works automatically for property list types-- for everything else, you have to implement NSCoding, or you get this error.
Copying a managed object ID's URI is probably reasonable if you want to copy the relationships. If you're having problems with temporary object IDs, do one of the following:
Save changes
Call obtainPermanentIDsForObjects:error: for the objects to get permanent IDs without saving.

RestKit many-to-many with Core Data: it works, but am I doing it right?

I'm new to RestKit. I'm trying to map a many-to-many relationship, between entities Space and User. For the purposes of this question, assume all the Space objects are in the Core Data store correctly already.
In the REST API, I can make a single call to get all the users for a given space. First of all, when I initialise my network fetching class, I set up a mapping appropriate for parsing a list of users:
RKManagedObjectMapping *teamMapping = [RKManagedObjectMapping mappingForEntity:[NSEntityDescription entityForName:#"User" inManagedObjectContext:self.manager.objectStore.primaryManagedObjectContext] inManagedObjectStore:self.manager.objectStore];
[teamMapping mapKeyPath:#"id" toAttribute:#"userID"];
[teamMapping mapKeyPath:#"name" toAttribute:#"name"];
teamMapping.primaryKeyAttribute = #"userID";
[self.manager.mappingProvider setMapping:teamMapping forKeyPath:#"users.user"];
Then, to populate the links for the users to the spaces, I do this:
NSArray *spaces = [self.managedObjectContext executeFetchRequest:[NSFetchRequest fetchRequestWithEntityName:#"Space"] error:nil];
for (QBSpace *space in spaces)
{
[self.manager loadObjectsAtResourcePath:[NSString stringWithFormat:#"space/%#/users", space.wikiName] usingBlock:^(RKObjectLoader *loader) {
loader.onDidLoadObjects = ^(NSArray *objects){
space.team = nil;
for (QBUser *user in objects)
{
[space addTeamObject:user];
}
};
}];
}
That is, I manually add the space->user link based on the returned array of objects.
Is that the correct way to do it? It seems to work fine, but I'm worried I'm missing a trick with regards to RestKit doing things automatically.
The returned XML for the file in question looks like
<users type="array">
<user>
<id>aPrimaryKey</id>
<login>loginName</login>
<login_name warning="deprecated">loginName</login_name>
<name>Real Name</name>
</user>
So there is nothing in the returned file to indicate the space that I'm trying to link to: I passed that in in the URL I requested, but there's nothing in the returned document about it, which is why I came up with this block based solution.
To all the RestKit users, does this look like an acceptable way to form many-to-many links?
If it works, it's ok?
You could think about having a Space custom ManagedObject. Have it respond to the RKObjectLoaderDelegate.
Then, when you get the reply, you could trigger the loadAtResourcePath from within its
objectLoader:didLoadObject:(id)object or objectLoader:didLoadObjectDictionary:
methods.
You could also make your Space class respond to the delegates from User and then tie them into their space at that point?
It might be better, but that would depend on what you are trying to achieve. Food for thought anyway. :)

Appending data to NSFetchedResultsController during find or create loop

I have a table view that is managed by an NSFetchedResultsController. I am having an issue with a find-or-create operation, however. When the user hits the bottom of my table view, I am querying my server for another batch of content. If it doesn't exist in the local cache, we create it and store it. If it does exist, however, I want to append that data to the fetched results controller and display it. I can't quite figure that part out.
Here's what I'm doing thus far:
The NSFetchedRequestController when initialized queries for the latest 100 results from the database (using setFetchLimit:). Even if there are 1000 rows, I only want 100 accessible at first.
Passing the returned array of values from my server to an NSOperation to process.
In the operation, create a new managed object context to work with.
In the operation, I iterate through the array and execute a fetch request to see if the object exists (based on its server id).
If the object doesn't exist, we create it and insert it into the operations' managed object context.
After the iteration completes, we save the managed object context, which triggers a merge notification on my main thread.
During the merge, the newly created objects from step 4 are inserted into the table, but any object that already existed and was just fetched does not. Here's the relevant code from my NSOperation
for (NSDictionary *resultsDict in self.results)
{
NSNumber *dbID = [NSNumber numberWithLong:[[resultsDict valueForKey:#"id"] longValue]];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:kResultEntityName inManagedObjectContext:moc]];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat: #"(dbID == %#)", dbID]];
NSError *error = nil;
NSManagedObject *newObject = nil;
// Query the data store to see if the object exists
newObject = [[moc executeFetchRequest:fetchRequest error:&error] lastObject];
[fetchRequest release];
// If it doesn't exist, create it.
if ((tweet == nil))
{
// Create the NSManagedObject and insert it into the MOC.
}
}
What I want to pass to my main thread is the newly created objects plus any existing objects that may have been fetched in the fetch request each time the loop iterates.
I feel like it's something simple I'm missing, and could use a nudge in the right direction.
At this point, any objects that weren't locally cached in my Core Data store before will appear, but the ones that previously existed do not come along for the ride.
Can you explain this a little? I am not sure what you mean by the ones that previously existed. Is it objects that didn't match the filter on your table that now do after the retrieval or are you saying that the previous objects disappear from the table?
Also, how are you implementing the delegate methods for the NSFetchedResultsController? Are you doing a simple table reload or are you inserting/moving rows?
Update
There are a couple of ways to do this but they would require some experimentation on your part. I would first play with the idea of "touching" the objects that were fetched. Perhaps updating a 'lastAccessed' date or something so that these objects will come across the merge as "updated". I suspect that is the easiest path.
Baring that, another option would be to broadcast a notification of those objects back to the main thread (using their NSManagedObjectID as the carrier across the thread boundaries) so that you can manually update them; however that is less than ideal.
Hey Justin, could your fetchLimit be causing this?
The NSFetchedRequestController when
initialized queries for the latest 100
results from the database (using
setFetchLimit:). Even if there are
1000 rows, I only want 100 accessible
at first.
You will still have a limit of 100 results on the NSFetchedResultsController no matter how many managed objects you insert & merge.
Do you have a sorting turned on? If so, some of the inserted managed objects might be showing up because they displace some of the existing 100 due to the ordering of results.
I've gone through the same issues with fetching "pages" of results, and went with a lower-bound constraint on my fetch (using the sorted attribute in an NSComparisonPredicate) and adjusting that with the last item in the most recent "page" of results.
I also tried the fetchLimit approach, and that worked too. You don't need to remove & rebuild the NSFetchedResultsController, you can just adjust the fetchLimit of the fetchRequest:
tableMaxItems += 100;
[myFRC.fetchRequest setFetchLimit:tableMaxItems];
Here is how I ended up fixing this. Prior to merging in the changes from my NSOperation's MOC, I iterate through the values stored in NSUpdatedObjectsKey and touch them with willAccessValueForKey. To get them into NSUpdatedObjects key I took Marcus' advice above and added a lastAccessed property that I set to the current date in the NSOperation if the object already existed in the persistent store..
- (void)mergeChanges:(NSNotification *)notification
{
NSAssert([NSThread mainThread], #"Not on the main thread");
NSSet *updatedObjects = [[notification userInfo] objectForKey:NSUpdatedObjectsKey];
for (NSManagedObject *object in updatedObjects)
{
[[managedObjectContext objectWithID:[object objectID]] willAccessValueForKey:nil];
}
[managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
}

What changes in Core Data after a save?

I have a Core Data based mac application that is working perfectly well until I save a file. When I save a file it seems like something changes in core data because my original fetch request no longer fetches anything. This is the fetch request that works before saving but returns an empty array after saving.
NSEntityDescription *outputCellEntityDescription = [NSEntityDescription entityForName:#"OutputCell"
inManagedObjectContext:[[self document] managedObjectContext]];
NSFetchRequest *outputCellRequest = [[[NSFetchRequest alloc] init] autorelease];
[outputCellRequest setEntity:outputCellEntityDescription];
NSPredicate *outputCellPredicate = [NSPredicate predicateWithFormat:#"(cellTitle = %#)", outputCellTitle];
[outputCellRequest setPredicate:outputCellPredicate];
NSError *outputCellError = nil;
NSArray *outputCellArray = [[[self document] managedObjectContext] executeFetchRequest:outputCellRequest
error:&outputCellError];
I have checked with [[[self document] managedObjectContext] registeredObjects] to see that the object still exists after the save and nothing seems to have changed and the object still exists. It is probably something fairly basic but does anyone know what I might be doing wrong? If not can anyone give me any pointers to what might be different in the Core Data model after a save so I might have some clues why the fetch request stops working after saving?
Edit
I have got as far as working out that it is the relationships that seem to be breaking after a save. If I omit the lines setting a predicate for the request, the request returns objects in the array. I have checked through the registeredObjects and it appears that the relationships are intact, but if I do something like save a file, re-open it and then check the registeredObjects the relationships are set to nil. I've opened a save file as an xml file and the relationships appear to be intact when the file is first saved.
I've added a screen shot of the part of the core data model were the relationships are broken. Does anyone have any idea why saving a file in core data might break the relationships? For reference I'm using the default implementation of save built into core data so there is no custom save code.
http://emberapp.com/splash6/images/littlesnapper/sizes/m.png
Edit
I have no -awakeFromFetch: methods that are triggering when this problem is caused.
I have sub-classed NSManagedObject for some of the problem objects, using the Core Recipes model for KVO:
+(void)initialize
{
if (self == [OutputCell class])
{
NSArray *nameKeys = [NSArray arrayWithObjects:#"cell", #"sheet", #"table", nil];
[self setKeys:nameKeys
triggerChangeNotificationsForDependentKey:#"cellTitle"];
NSArray *measuresKeys = [NSArray arrayWithObjects:#"fivePercentile", #"maximum", #"mean", #"median",#"minimum",#"ninetyFivePercentile",#"standardDeviation",nil];
[self setKeys:measuresKeys
triggerChangeNotificationsForDependentKey:#"analysisResults"];
}
}
This method doesn't seem to be firing during or after a save so it doesn't seem to be this that is causing the problem. I'm currently going through all the other methods in the code to find if any of them happen to get called during or after a save.
Edit
Following on from Marcus' suggestion below I've managed to make a fetch request fail before the model is saved. My problem now is the message this getting returned in the console when it fails:
HIToolbox: ignoring exception '+entityForName: could not locate an NSManagedObjectModel for entity name 'OutputCell'' that raised inside Carbon event dispatch
The console message is logged following this call:
NSEntityDescription *outputCellEntityDescription = [NSEntityDescription entityForName:#"OutputCell"
inManagedObjectContext:[[self document] managedObjectContext]];
Should the extra ' following the OutputCell in the console message be there? Do objects normally have this extra ', or has it come from somewhere? If it has come from somewhere and is causing the fetch request to fail, does anyone have any bright ideas where this might have come from or how I might track it's source down?
Sounds like you are setting something to nil somewhere and causing you to get nil back. I would walk through your save and fetch code in the debugger and look for objects being set to nil when you do not expect it.
update
Do you have any code anywhere that can be manipulating the relationships? Perhaps something in the -awakeFromFetch: that is causing the relationships to get corrupted?
If they are saving correctly the first time and then failing then that truly points at something in your code corrupting those relationships. Are you subclassing NSManagedObject for these objects? If so are you by chancing overriding the -init... method?
update
That last tick should definitely not be there. Check your fetch request, this might all boil down to a simple typo in a string somewhere...

Resources