From UIManagedDocument to traditional Core Data stack - ios

I created a new App using UIManagedDocument. While on my devices everything is fine, I got a lot of bad ratings, because there are problems on other devices :(
After a lot of reading and testing, I decided to go back to the traditional Core Data stack.
But what is the best way to do this with an app, that is already in the app store?
How can I build this update? What should I take care of?
Thanks,
Stefan

I think you may be better off to determine your issues with UIManagedDocument and resolve them.
However, if you want to go to plain MOC, you only have a few things to worry about. The biggest is that the UIMD stores things in a file package, and depending on your options you may have to worry about change logs.
In the end, if you want a single sqlite file, and you want to reduce the possibility of confusion, you have a class that simply opens your UIManagedDocument, and fetches each object, then replicates it in the single sqlite file for your new MOC.
Now, you should not need a different object model, so you should not have any migration issues.
Then, just delete the file package that holds the UIManagedDocument, and only use your single file sqlite store.
Basically, on startup, you try to open the UIManagedDocument. If it opens, load every object and copy it into the new database. Then delete it.
From then, you should be good to go.
Note, however, that you may now experience some UI delays because all the database IO is happening on the main UI thread. To work around this, you may need to use a separate MOC, and coordinate changes via the normal COreData notification mechanisms. There are tons of documents, examples, and tutorials on that.
EDIT
Thanks for your answer. My problem with these issues is, that I'm not
able to reproduce them. All my Devices are working fine. But I got a
lot mails, about problems like this: - duplicate entries - no data
after stoping and restarting the app - some say, that the app works
fine for some days and stops working(no new data). These are all
strange things, that don't happen on my devices. So for me the best
way is to go back to plain MOC. My DB doesn't hold many user generated
data, all the data is loaded from a webservice, so it's no problem to
delete the data and start of using a new DB. – Urkman
Duplicate entries. That one sounds like the bug related to temporary/permanent IDs. There are lots of posts about that. Here is one: Core Data could not fullfil fault for object after obtainPermanantIDs
Not saving. Sounds like you are not using the right API for UIManagedDocument. You need to make sure to not save the MOC directly, and either use an undo manager or call updateChangeCount: to notify UIManagedDocument that it has dirty data that you want to be saved. Again, lots of posts about that as well. Search for updateChangeCount.
However, you know your app best, and it may just be better and easier to use plain Core Data.
Remember, if you are doing lots of imports from the web, to use a separate MOC, and have your main MOC watch for DidSave notifications to update itself with the newly imported data.

UIManagedDocument is a special kind of document, an UIDocument subclass, that stores its data using Core Data Framework. So it combines the power of document architecture and core data capabilities.
You can read more about document based architecture from Document Based App Programming Guide for iOS and I recommend WWDC2011 Storing Documents in iCloud using iOS5 session video. I also recommend Stanford CS193P: iPad and iPhone App Development (Fall 2011) Lecture 13.
What is created when you call saveToURL:forSaveOperation:completionHandler: is an implementation detail of UIManagedDocument and UIDocument and you should not really worry or depend on it. However in current implementation a folder containing an sqlite database file is being created.
No. All entities will be contained in a single database file also more generally called: a persistent store. It is possible to use more than one persistent store, but those are more advanced use cases and UIManagedDocument currently uses one.
UIManagedDocument's context refers to a NSManagedObjectContext from underlying Core Data Framework. UIManagedDocument actually operates two of those in parallel to spin off IO operations to a background thread. When it comes to the nature of a context itself here's a quote from Core Data Programming Guide:
You can think of a managed object context as an intelligent scratch pad. When you fetch objects from a persistent store, you bring temporary copies onto the scratch pad where they form an object graph (or a collection of object graphs). You can then modify those objects however you like. Unless you actually save those changes, however, the persistent store remains unaltered.
But it really is a good idea to take a look at the lectures and other material I posted above to get a general picture of the technologies used and their potential value to you as a developer in different situations.

Related

Need some knowledge on Core Data - NSManagedObject usages

Just a quick question regarding loading data into the app through Core Data - I have already implemented Core Data and app is pretty much running just as it was before I started using it.
In short, when app launches I am fetching all the Entities into a Manager script that stores each object into different arrays and when the app uses the objects the Manager script will pass these arrays to other scripts.
My question is, does this seem like a bad method while using Core Data? Should I just be fetching the Entities when the scripts want them or its fine 'pre-fetching' from the start? This data is limited (to a point) and doesn't change during runtime.
Also, since I have all the entities in different arrays in the Manager script, I am sorting/filtering these arrays by predicates when a script needs something done. (which means I am never using a Core Data fetch with predicate since all the data is already available in the Manager's arrays)
App is already done, was just trying to make performance improvements and by adding Core Data, there is a huge boost. This is kind of my last question (at the moment) and I'm not really sure on the answer since I have never used Core Data before.
Thank you
It is fine.
There are three main drawbacks to prefetching:
You can take up too much memory and crash.
If an entity is deleted and you keep a pointer to it, the app will crash when you try to use that managedObject
Loading might take a very long time if there is a lot of data.
You said "This data is limited (to a point) and doesn't change during runtime" so it appears that none of these issue apply to you.
That being said I am not sure that you are really getting any benefit from core data in this setup. Core data in general scales very well, but your setup will not. You could just as easily store all your information in a file and load it all into memory when the app starts. I trust that you getting other benefits from core data that are not stated in your question.

How to create snapshot of CoreData state?

Background story
I am developing a big iOS app. This app works under specific assumptions. The main of them is that app should work offline with internal storage which is a snapshot of last synchronized state of data saved on server. I decided to use CoreData to handle this storage. Every time app launches I check if WiFi connection is enabled and then try to synchronize storage with server. The synchronization can take about 3 minutes because of size of data.
The synchronization process consists of several stages and in each of them I:
fetch some data from the server (XML)
deserialize it
save it in Core Data
Problem
Synchronization process can be interrupted for several reasons (internet connection, server down, user leaving application, etc). This may cause data to be out-of-sync.
Let's assume that synchronization process has 5 stages and it breaks after third. It results in 3/5 of data being updated in internal storage and the rest being out of sync. I can't allow it because data are strongly connected to each other (business logic).
Goal
I don't know if it is possible but I'm thinking about implementing one solution. On start of synchronization process I would like to create snapshot (some kind of copy) of current state of Core Date and during synchronization process work on it. When synchronization process completes with success then this snapshot could overwrite current CoreData state. When synchronization interrupts then snapshot can be simply aborted. My internal storage will be secured.
Questions
How to create CoreData snapshot?
How to work with CoreData snapshot?
How to overwrite CoreDate state with snapshot?
Thanks in advice for any help. Code examples, if it is possible, will be appreciated.
EDIT 1
The size of data is too big to handle it with multiple CoreData's contexts. During synchronization I am saving current context multiple times to cleanup memory. If I do not do it, the application will crash with memory error.
I think it should be resolved with multiple NSPersistentStoreCoordinators using for example this method: link. Unfortunately, I don't know how to implement this.
You should do exactly what you said. Just create class (lets call it SyncBuffer) with methods "load", "sync" and "save".
The "load" method should read all entities from CoreData and store it in class variables.
The "sync" method should make all the synchronisation using class variables.
Finally the "save" method should save all values from class variables to CoreData - here you can even remove all data from CoreData and save brand new values from SyncBuffer.
A CoreData stack is composed at its core by three components: A context (NSManagedObjectContext) a model (NSManagedObjectModel) and the store coordinator (NSPersistentStoreCoordinator/NSPersistentStore).
What you want is to have two different contexts, that shares the same model but use two different stores. The store itself will be of the same type (i.e. an SQLite db) but use a different source file.
At this page you can see some documentation about the stack:
https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/InitializingtheCoreDataStack.html#//apple_ref/doc/uid/TP40001075-CH4-SW1
The NSPersistentContainer is a convenience class to initialise the CoreData stack.
Take the example of the initialisation of a NSPersistentContainer from the link: you can have the exact same code to initialise it, twice, but with the only difference that the two NSPersistentContainer use a different .sqlite file: i.e. you can have two properties in your app delegate called managedObjectContextForUI and managedObjectContextForSyncing that loads different .sqlite files. Then in your program you can use the context from one store to get current data to show to the user and you can use the context that use the other store with a different .sqlite if you are doing sync operations. When the sync operations are finally done you can eventually swap the two files and after clearing and reloading the NSPersistentContainer (this might be tricky, because you will want to invalidate and reload all managed objects: you are switching to an entirely new context) you can then show the newly synced data to the user and start syncing again on a new .sqlite file.
The way I understand the problem is that you wish to be able download a large "object graph". It is however so large that it cannot be loaded at once in memory, so you would have to break it in chunks and then merge it locally into to Core data.
If that is the case, I think that's not trivial. I am not sure I can think of direct solution without understanding the object relations and even then it may be really overwhelming.
An overly simplistic solution may be to generate the sqlite file on the backend then download it in chunks; it seems ugly, but it serves to separate the business logic from the sync, i.e. the sqlite file becomes the transport layer. So, I think the essence to the solution would be to find a way to physically represent the data you are syncing in a format that allows for splitting it in chunks and that can afterwards be merged into a sqlite file (if you insist on using Core data).
Please also note that as far as I know Amazon (https://aws.amazon.com/appsync/) and Realm (https://realm.io/blog/introducing-realm-mobile-platform/) provide background sync of you local database, but those are paid services and you would have to be careful not be locked in (should not depend on their libs in your model layer, instead have a translation layer).

Singletons vs Core Data

This question is not about the technical problem, but rather the approach.
I know two more or less common approaches to store the data received from the server in your app:
1) Using managers, data holders etc to store the data. They are most often some kind of singleton and are used to store the models received from the server. (E.g. - the array of the posts/places/users) Singletons are needed to be able to access the data from any screen. I think the majority of apps uses this approach.
2) Using Core Data (or maybe Realm) as in-memory storage. This approach avoids having singletons, but, I guess, it is a bit more complex (and crash risky) to maintain and support.
How do you store data and why?
P.S. Any answers would help. But big "thank you" for detailed ones, with reasons.
The reason people opt to use Core Data/Relam/Shark or any other iOS ORM is mainly for the purpose of persisting data between runs of the app.
Currently there are two ways of doing this, for single values and very small (not that I encourage it) objects you can use the UserDefaults to persist between app launches. For a approach closer to a database, infact in the case of Core Data and SharkORM, they are built on top of SQLite, you need to use an ORM.
Using a manager to store an array of a data models will only persist said models for the lifetime of the app. For example when the user force quits the app, restarts their device or in some circumstances when iOS terminates your app, all that data will be lost permanently. This is because it is stored in RAM which is volatile memory, rather than in a database on the disk itself.
Using a database layer even if you don't specifically require persistence between launches can have its advantages though; for instance SharkORM allows you to execute raw SQL queries on your objects if you don't want to use the built in powerful query builder. This can be useful to quickly pull the model you are interested in rather than iterating through a local array.
In reply to your question, how do I store data?
Well, I use a combination of all three. Say for instance I called to an API for some data which I wanted to display there and then to the user, I would use a manager instance with an array to hold the data model.
But on the flipside if I wanted to store that data for later or if I needed to execute a complex query on it, I would store it on disk using Shark.
If however I just wanted to store whether or not the user had seen my on boarding flow I would just persist a boolean value into UserDefaults.
I hope this is detailed enough for you.
CoreData isn't strictly "in-memory". You can load objects into your data model and save them into their context, then they might actually be on disk and out of main memory, and they can easily be brought back via fetch requests.
Singletons, on the other hand, do typically stay in main memory all the time until the user terminates the app. If you have larger objects that you are storing in some data structure (e.g. full resolution images when all you really needed was a thumbnail), this can be quite a resource hog.

CoreData concurrency (for sync with CloudKit)

In one of my apps I would like to enable sync via CloudKit. The app itself stores the data using CoreData. I cannot use CoreData+iCloud because I need to be able to track changes which were made which is not possible with the above mentioned setup.
The obvious challenge which I have relates to the fact that CloudKit operations will be happening on the background thread and so I need to support concurrency with my CoreData stack.
Lets assume that I have some CoreData entity which I want to sync with CloudKit. To do background sync I need to create a separate managed object context. When this context fetches changes made to my entity on other devices I want to save these changes.
However, the problem is that during the execution of fetch user could have changed some attributes of a given entity and I am now stuck with this entity having some important information on both contexts. I cannot just choose between which one to save - I need to merge the changes.
Unfortunately, I do not understand which approach I need to take to be able to manually sync these changes. I have already checked the possible techniques (parent-child, multiple contexts, multiple store coordinators) but I still don't understand which approach I need to choose.
Can someone help me to resolve this confusion?
The most ideal solution for me would be such that I would get a conflict whenever sync context tries to merge changes to the main context which also had some changes. In this case I could easily decide which attributes should be updated, but I really don't know how this can be done...
In Apple WWDC 2014 they did a session on just this in effect. Here is the transcript, you can find the video easily too; assuming your Apple Developer.
http://asciiwwdc.com/2014/sessions/231
In in short an Apple engineer goes over a very simple example of using change tokens; an industry standard solution to resolving problem of sorting out data change conflicts.
The Ray Wenderlich web site also has some excellent VIDEOs on cloud kit and core data, it is a subscription service, although well worth the money at just 20$ a month, and no I have no affiliation with him; I'm just a subscriber. Google him and your find his website.

Sharing a Core Data stack and data between App and Extension in iOS8

I created a framework to share my data objects between the App and the extension. This includes the data model and the sqlite file with my Core Data db.
I am concerned of what might happen if both App and Extension try to access this shared sqlite db.
What could go wrong if the App is making some changes to the db in the background while the extension is using it?
What's the best practice in this case?
As #CL notes, SQLite is fine with this. But you're not using SQLite directly, so you may need to do some Core Data-level work to maintain consistency. With an iOS app and an extension, you have two separate processes that can make changes to the data. Your code needs to account for this.
If your app extension only displays data (for example, a "today" extension that only displays data created in the app), you probably don't need to do anything special. If your app is running in the background and creating new data while the extension is visible, it's possible that the extension's data could be slightly out of date. If that's important, you can refresh it. But today extensions typically aren't visible for very long, so it's probably not worthwhile. In this case I'd use NSReadOnlyPersistentStoreOption when setting up the extension's Core Data stack just to be clear about the intention and prevent inadvertent changes.
If your app extension creates new data or modifies existing data, your app needs to be aware of this and respond appropriately. What changes you would make will depend on how exactly the extension handles the shared data. For modified data, your app probably needs to call refreshObject:mergeChanges: on any in-memory managed objects with NO as the second argument. It also probably needs to redo any fetches where the changes might affect a search predicate. That'll ensure you're getting the most recent updates. For new data you would need to re-fetch any data the app is working with to get new additions/deletions. A good time to check would be when the application comes to the foreground (i.e. when UIApplicationWillEnterForegroundNotification is posted).

Resources