Resolving Conflicts in Core Data with iCloud - iphone

I'm writing an app that uses Core Data and is synced with iCloud. To do this, I have a UIManagedDocument that I set up as shown below:
UIManagedDocument *document = [[UIManagedDocument alloc] initWithFileURL:[self iCloudStoreURL]];
document.persistentStoreOptions = #{NSPersistentStoreUbiquitousContentNameKey: [document.fileURL lastPathComponent], NSPersistentStoreUbiquitousContentURLKey: [self iCloudCoreDataLogFilesURL], NSMigratePersistentStoresAutomaticallyOption: #YES, NSInferMappingModelAutomaticallyOption : #YES};
self.mydoc = document;
[document release];
[document.managedObjectContext setMergePolicy:NSMergeByPropertyObjectTrumpMergePolicy];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(documentContentsChanged:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:document.managedObjectContext.persistentStoreCoordinator];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(documentStateChanged:) name:UIDocumentStateChangedNotification object:document];
if (![[NSFileManager defaultManager] fileExistsAtPath:[self.mydoc.fileURL path]]) {
// does not exist on disk, so create it
[self.mydoc saveToURL:self.mydoc.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
[self populateTable];//synchronous call. few items are added
[self iCloudIsReady];
}];
} else if (self.mydoc.documentState == UIDocumentStateClosed) {
// exists on disk, but we need to open it
[self.mydoc openWithCompletionHandler:^(BOOL success) {
[self iCloudIsReady];
}];
} else if (self.mydoc.documentState == UIDocumentStateNormal) {
// already open and ready to use
}
}
My issue with this approach is that I keep getting "Optimistic locking failure" when running the app in two devices. I read in Apple's Core Data documentation that a way to "avoid" this kind of issue was to set up the merge policy to NSMergeByPropertyObjectTrumpMergePolicy, something that I am already doing but for some reason is not working.
One thing I can't find is how to fix this. For example, if this is something that could happen, my app should be at least aware and prepared to handle this behavior. But I have no idea on how to handle this. For example, how do I get the conflicting objects and resolve them? Because every time this failure happens, I start getting UIDocumentStateSavingError when trying to save the document and the only way to stop getting this error is by killing the app and re-launching it.

I finally figured this out (at least, I think I did). Apparently, on iOS6+ (I have no idea about iOS5) UIManagedDocument takes care of all the merging for you. So, the observer below, which was only responsible for calling "mergeChangesFromContextDidSaveNotification:" was in fact merging what was just merged.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(documentContentsChanged:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:document.managedObjectContext.persistentStoreCoordinator];
...
- (void)documentContentsChanged:(NSNotification *)notification {
[self.managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
}
Calling "mergeChangesFromContextDidSaveNotification:" was the line responsible for triggering the "Optimistic locking failure". I removed it and everything started working as expected. Unfortunately this only lasted a couple of hours. Now I keep getting the "iCloud Timed Out" error, but this one I'm sure it's Apple's fault.
Anyway, after a ton of bugs and three different iCloud + Core Data approaches, I think I will hold on integrating iCloud into my app. It is far too unstable and buggy. I really wish Apple could have fixed this with iOS6, iCloud + Core Data is a very powerful tool, unfortunately, it is not ready yet.
Thanks to everyone who tried to help.

Related

UIManagedDocument CompletionHandler & NSNotification

I am using Core Data and was wondering if I am doing things correctly. I am opening my UIManagedDocument from a singleton object using the completion handler and block below.
[[self managedDocument] openWithCompletionHandler:^(BOOL success) {
if(success) {
NSLog(#"DOCUMENT: Success, Opened ...");
// TODO: Things to do when open.
// ...
// ...
}
}];
On my UIViewController I have setup an observer to watch for a UIDocumentStateChangedNotification to indicate that I can start working with the document.
- (void)awakeFromNib {
NSLog(#"%s", __PRETTY_FUNCTION__);
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self selector:#selector(documentIsReady) name:UIDocumentStateChangedNotification object:nil];
}
This seams to work just fine, but I am conscious that I am not using the callback block. One solution might be to create my own notification and post that from the block, it does the same thing essentially but just makes the code more obvious to read. Any comments would be much appreciated.
I'd say that if you only need to notify one controller, once, and only when the document is opened (you have an app that uses a single UIManagedDocument that gets passed between controllers, like the CS193P demo), it would be better to leave only the code inside the completion block.
However, if your app is going to open and close the document many times, and multiple controllers have to be aware of that change, you should use notifications.

NSPersistentStoreDidImportUbiquitousContentChangesNotification not being notified

If an entry is changed in core data on another device, NSLog messages show that it's noticed the changes, but NSPersistentStoreDidImportUbiquitousContentChangesNotification is not being called. It takes until a save on my first device for it to know to update my tableview.
This is my code:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(iCloudUpdates:)
name:NSPersistentStoreDidImportUbiquitousContentChangesNotification
object:nil];
Anybody know why this might not be working?
First option:
If your problem is a delay in updating both devices, that is normal behavior, Apple doesn't guarantee update timing, but it is usually fast.
If on the other side the problem is that iCloudUpdates method is not called make sure that signature is correct, should be :
-(void)iCloudUpdates:(NSNotification*)notification {
// do your stuff here
}
Second option:
at time of writing, iOS 5 has big big problem with iCloud and CoreData, I recently shipped my application without iCloud support.
If you want to know what is going on turn logging on for both CoreData and iCloud by putting:
-com.apple.CoreData.SQLDebug 1
-com.apple.coredata.ubiquity.logLevel 3
in your scheme manager, under run->arguments tab.
If you see some strange errors in 'destination' device that's the case of iCloud not working for being bugged.
I think the problem with your code is that in the "addObserver" you've set the object to nil. The object should be your persistentStoreCoordinator as shown below.
__weak NSPersistentStoreCoordinator *psc = self.context.persistentStoreCoordinator;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(iCloudUpdates:)
name:NSPersistentStoreDidImportUbiquitousContentChangesNotification
object:psc];

iCloud sync not sending data through ubiquity container

I have been using iCloud in my apps for a while now and am recently having an issue where devices refuse to talk to each other. Or at least that's what I thought until I started logging the methods where the merging takes place. My persistentStoreCoordinator is set up as described in a previous question of mine.
The problem is the following. When setting up my managedObjectContext, I add an observer to it to view the NSPersistentStoreDidImportUbiquitousContentChangesNotification notification like follows:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(mergeChangesFrom_iCloud:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:coordinator];
where coordinator is the set up as NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator].
My iCloud methods are as follows:
- (void)mergeiCloudChanges:(NSNotification *)note forContext:(NSManagedObjectContext *)moc {
NSLog(#"insert %#", [[note userInfo] valueForKey:#"inserted"]);
NSLog(#"delete %#", [[note userInfo] valueForKey:#"deleted"]);
NSLog(#"update %#", [[note userInfo] valueForKey:#"updated"]);
[moc mergeChangesFromContextDidSaveNotification:note];
NSNotification *refreshNotification = [NSNotification notificationWithName:#"RefreshAllViews" object:self userInfo:[note userInfo]];
[[NSNotificationCenter defaultCenter] postNotification:refreshNotification];
}
- (void)mergeChangesFrom_iCloud:(NSNotification *)notification {
NSLog(#"merging changes");
NSManagedObjectContext *moc = [self managedObjectContext];
[moc performBlock:^{
[self mergeiCloudChanges:notification forContext:moc];
}];
}
So now we have the actual problem
At first, syncing went flawlessly. Data from one device was changed, then that change appeared on the other device. But now, nothing. The curious part is in those logs you see in mergeiCloudChanges:forContext:. The merge actually occurs. I see this triggered. But the insert, delete, and update parts of the merge note are ALWAYS without content. So the merge occurs, but with no data. For the life of me, I cannot figure out why this is or how to get it to sync properly again. Any help would be more than appreciated.
Note: I am also using the NSUbiquitousKeyValueStoreDidChangeExternallyNotification notification for my NSUbiquitousKeyValueStore (which I use to sync the NSUserDefault key-values), and those notifications transfer over and update without any hiccups at all, which confuses me even more as to why the persistentStoreCoordinator notifications are blank.
I truly hope someone has seen/experienced this before because after two weeks exhausting every avenue I can think of to find and fix this on my own, I feel I am now at a standstill.
I've got this one figured out. Basically, the transaction logs appeared to be corrupted or misplaced. I have reworked a way to resycn devices and will be posting the results immediately on a previous question of mine

Wait for result without stopping UI

I have an iPad app, and I want to do this
-(IBAction) clicked {
image=download(#"http://....."); // this is on the main thread
}
The download function is going to call a whole bunch of non blocking functions to download a file from the internet, but download itself shouldn't return until the image is downloaded.
While the program is waiting for the download at the image=download(...) line above, I want the UI to be able to still function, for example be able to scroll a UITableView, click another button etc.
So what I did was this inside the download function I used a RunLoop
-(void) download:(NSString *)url
{
BOOL stillDownloading=TRUE;
while(stillDownloading) {
stillDownloading=downloadAFwBytes(...);
CFRunLoopRunInMode(kCFRunLoopCommonModes, 0, YES);
}
}
I thought the CFRunLoopRunInMode function will keep pumping UI messages, touches, scrolls through the main UI thread so that the UI will keep working and not freeze until the download finished, but for some reason, it only works for a short time, and eventually the UI freezes.
Do you know why, or how to fix?
The download function is called everywhere in the program, that expects it to wait for the download, so I can't change it to non blocking at the moment.
The direct answer to your question is, no, this is not what CFRunLoopRunInMode does. What you are effectively trying to do is have the current run loop "yield" so execution can continue while the loading operation continues. This is not how iOS and run loops work. Your download function blocks the thread it is on until downloading is complete so the only solution to your issue is to change the implementation so that downloading occurs on a background thread and the objects that care are notified when it is complete. Here's a relatively small change that can get you on the right track. This overall topic (concurrency, managing background tasks) is a bigger discussion and there are different considerations/tradeoffs. I'll cut to the chase and hopefully get you on the right track.
Define a couple NSNotification's that your download method can post for interested objects to observe:
// in the .h file of the class performing the download
extern NSString * const MyClassLoadingDidStartNotification;
extern NSString * const MyClassLoadingDidFinishNotification;
// in the .m file of the class performing the download
NSString * const MyClassLoadingDidStartNotification = #"MyClassLoadingDidStart";
NSString * const MyClassLoadingDidFinishNotification = #"MyClassLoadingDidFinish";
In your download routine, do the download in the background and post the appropriate notifications:
-(void) download:(NSString *)url
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:MyClassLoadingDidStartNotification object:self];
BOOL stillDownloading=TRUE;
while(stillDownloading) {
stillDownloading=downloadAFwBytes(...);
}
[[NSNotificationCenter defaultCenter] postNotificationName:MyClassLoadingDidFinishNotification object:self];
});
}
In any object that initiates a download, observe and handle the notifications
// in any class that initiates a download
- (void)init...
{
self = [super init...];
if (self) {
// other initialization
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(didStartLoading:) name:MyClassLoadingDidStartNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(didFinishLoading:) name:MyClassLoadingDidFinishNotification object:nil];
}
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:MyClassLoadingDidStartNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:MyClassLoadingDidFinishNotification object:nil];
}
- (void)didStartLoading:(NSNotification *)notification
{
// update UI to show loading status (make sure you do UI changes on main thread)
// optionally check notification.object to ensure it's the loader class instance you care about
}
- (void)didFinishLoading:(NSNotification *)notification
{
// update UI to show loading status (make sure you do UI changes on main thread)
// optionally check notification.object to ensure it's the loader class instance you care about
}
Keep in mind that this is a very basic starting point. As you learn more and decide what you need you will definitely customize it. For example, you may want to add error handling, limit concurrent loading operations, provide other loading status, etc.
There are some architecture concerns with your question, but to properly download an image in the background and load it into a UIImageView or use it in any other way, I'd suggest taking a look at AFNetworking and read through their sample code for downloading resources.
Can you request to download the image on the background and then, return a static image asap in your method?
This way, the main thread returns fast and depending on your architecture, your background thread can update the image once it got it?
I think we need more details on your code (your download method is void so how is the downloaded data used?) to be able to really help.
Along with the 3 other guys telling you the same thing, I'll tell you to forget about your own run loop model, and just use the async download capabilities (assuming you're downloading over the net). You don't even have to build a thread, just start the async downloads and they will tell you when they're done. If you don't have the time to code it right, when will you have the time to fix your code?
Not sure if this is solved yet but can't you use?
[self.operationQueue addOperationWithBlock:^{
[self MethodName];
}];
and when you want something to happen in the UI like table updates then put this in the method code:
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
////perform something here ////
}];
hope this helps.

How do we prevent "CoreData could not fulfill a fault"?

We get "CoreData could not fulfill a fault" every once in a while. We have read through the Apple documentation but are unclear on what is allowed to be retained. We have been very careful about creating one context per thread, etc. However, one thing our app is doing is we are retaining NSManagedObjects on our UIViewControllers (usually via a NSArray or NSDictionary). I'm guessing what's going on is the object relationships are changing and we are not handling the appropriate notification.
Does anyone have any suggestions on the better design with regards to Core Data? When we get the error, I cannot see that we actually deleted anything from the context to cause the fault. Is it necessary to handle NSManagedObjectContextObjectsDidChangeNotification on our UIViewControllers if they are retaining state? Any suggestions would be appreciated.
You can register for change notifications in Core Data. This will allow you to update your managed objects when they change. See the Core Data Docs for more info. You're going to be interested in 2 methods to register and respond to changes:
[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(mergeChanges:)
name:NSManagedObjectContextDidSaveNotification
object:(your NSManagedObjectContext)];
The mergeChanges selector (your method) will call the following method to synchronize any changes from other threads. It will look something like this:
- (void)mergeChanges:(NSNotification *)notification{
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
// Merge changes into the default context on the main thread
[context performSelectorOnMainThread:#selector(mergeChangesFromContextDidSaveNotification:)
withObject:notification
waitUntilDone:YES];
}