Multiple Persistent Store Coordinator Core Data - ios

At the moment i have one Persistent Store Coordinator which is backed up by a sql database. I have a lot of Entities in it. When i change the Model i try to use leightweight migration. If it failes i just delete everything and set it up again. For now this works fine. Now lets say i have to save some kinde of Bookmarks. Since you can have multiple bookmarks i think it is the best to save this also with core data. However in this case i need a real migration strategy so the user does not lose its bookmarks.
I'm thinking about creating a seperate persistent store coordinator which only contains the bookmark entity. With this one i could then do mirgations if necessary and the other perstitent store can be used as it is without migration.
Is this possible and recommended ? Or are there any pitfalls i have to watch out for. I hope i could explain my situation correctly. I was also thinking about saving the bookmarks with NSCoding but i'm not really sure which would be better in this case.
Any help is appreciated.

It is entirely possible. It's certainly a good idea to separate the static data that is just downloaded from the server (because it shouldn't be backed up) and the user created data (that should be).
Your main pitfalls are around ensuring that you keep the stores / contexts separate and that your code properly names things so it's obvious what you're working with.
If you have only a few bookmarks, they are small and they are usually all loaded at the same time then NSCoding is an ok option. If you have many, they are big or infrequently loaded then it isn't a great option.

Related

Usage of Core Data other than a Database

i am new to this Core data. When i search for tutorials, I'm seeing this sentence Core Data is not a database everywhere on the internet.
If it is not a database, why are we using it as a database?
For what purpose Core Data is initially created?
Is there any other way Core Data was used before/will be used in
future (Other than as a DB)?
Sorry for my English.
Thanks for the time.. (:
Actually Core Data is a bridge between the code and the underlying database (like SQLite or XML...). Core Data is not a database, but uses SQLite (or XML...) for persistence. The main purpose of Core Data is to manage memory objects and object graphs easily without having to do it manually through a SQLite library for instance. It is possible to use Core Data without persistence is you want (using In-Memory stores).
Here is the documentation : https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/index.html#//apple_ref/doc/uid/TP40001075-CH2-SW1
Bye!
If it is not a database, why are we using it as a database?
"We" are not necessarily doing so, depending on who you mean by "we". Core Data can be used in a database-like manner, keeping in mind the Core Data vs. SQL differences others have noted. But that's not the only possible use.
Statements that Core Data isn't a database are mostly intended to prevent people from thinking of Core Data in the same sense as SQL. That sort of thinking leads to badly designed data models, since the approach is different. It can be used as a database in the generic sense of the storing structured data but it's important to not assume that it works like other databases you may have used.
For what purpose Core Data is initially created?
Is there any other way Core Data was used before/will be used in future (Other than as a DB)?
Core Data was created to fill what might have been perceived as a missing piece in Apple's frameworks. They generally take the MVC approach. There were classes to help in designing and implementing views (in these pre-iOS days that meant AppKit) and with controller classes (for example NSArrayController, also an OS X class). But model support was limited to NSCoding, which required a lot of repetitive code. Custom solutions also had trouble scaling to large amounts of data-- for example NSCoding doesn't help you load only part of a large document graph, because it recursively works its way through the entire object hierarchy.
Core Data was added with the purpose of making it easier to design and implement the model layer of an app. It's no accident that the document you edit to design the data is called a data model and not a schema.
The idea was (and is) that you could
Design your data model visually in Xcode
Create and use instances of your model objects
Read and save those objects in a file
...all without ever needing to write your own code to figure out how to convert your model objects to and from something that could be written into a file, or with the mechanics of opening a file, reading/writing it, and saving it. You'd just create objects as needed and then call save on NSManagedObjectContext. The small bit of code that was concerned with locating and opening the file was all pretty much the same in any app, so while it was still required it was mostly no longer the app developer's concern (and in iOS 10, NSPersistentContainer eliminates even this). You'd also get the benefit of only needing to load the parts of your object graph that you currently needed instead of loading everything every time.
As you've noticed, in practice Core Data is commonly used more or less like a database, and it works for that. But it's not designed to be limited to such uses.
Yes it is true , Core data is not a Database, though internally it saves data using sqlite. We use Coredata for persistent data which means we should be able to save the data and use it even after closing and reopening the app. There are various ways to store data like Sqlite,Plist,UserDefaults and CoreData. Coredata does not maintain any relations like SQlite. It means there are no keys like primary and foreign etc. Coredata allows you to deal with data in Object Oriented Approach. You can easily work with data operations even you don't have knowledge about DB queries.

Core Data ordeal

A few weeks ago, I decided to learn Core Data for my new project and apply it to my entire model. There was a steep learning curve, but eventually I got familiar with the stack and I'm now rather comfortable with at least the basic concepts and the few common pitfalls such as thread concurrency.
I have to say, the first few weeks after getting comfortable where pretty amazing. NSFetchedResultsController give you a good way to communicate between my model and my controllers. However the more I use Core Data, the more annoying it gets.
As a concrete example, my app fetches a few pieces of data from my server (the posts) which appear in a feed. Each post has an owner, of class User, which I also fetch from the server. Now, Core Data has been great for managing the realtionship between a post and a user. The relationship is updated automatically and getting the post's origin is as simple as calling post.owner. However, there are also inconveniences:
1.Core Data forces objects to the disk that I do not want forced to the disk. This is probably the main issue. With the posts, I do not want them to be forced to disk, and would rather make calls to the server again. Why? Because the more posts I store persistently, the more housekeeping there is to do. A post can be edited, deleted, flagged, etc... and keeping those posts locally means having to plan updates.
2.Having to constantly worry about concurrency of contexts, objects and the likes. I wrote an object factory that always returns objects on the right thread and the right context, but even then bugs occur here and there, which quickly becomes frustrating.
3.Decreased performance. Perhaps the least important one at this point, going from cached objects to Core Data has taken a (barely noticeable) toll on the performance of my application (most notably the feed).
So what are your recommendations regarding Core Data? Would you suggest a different approach to Core Data?
I was thinking of a hybrid caching + Core Data where I store the information I will actually use many times (such as users) persistently and then use the RAM for things like posts, or simply creating posts without an NSManagedContext. Input welcome!
Core Data forces objects to the disk that I do not want forced to the disk.
It does no such thing. If you don't want to save your Post objects to the persistent store, don't put them in Core Data and don't make them managed objects. Your User object can have a posts property even if the Post object is not managed by Core Data. Managed objects can have properties of any type, not only to other managed objects.
Having to constantly worry about concurrency of contexts, objects and the likes.
Concurrency is complex no matter how you model your data. It's a fundamentally complex problem. You're encountering it with Core Data because you're using Core Data. If you use something else, you'll deal with it there.
Decreased performance.
"Product" menu --> "Analyze" and run Instruments to find out why. There's no reason this should happen, and you have the tools to discover what's actually going on.

Data Storage options for iOS

I am building an app that will require an offline mode when unable to get a wifi or data connection.
I am wondering what is the best solution for the following scenario.
Lets say my app allows users to view, add , amend an event on a calendar.
For the app to work off line i only need to store the current days worth of events. This could be be between 1 - 10 events. Each event will have a name, description and various other small properties.
I have been looking at coreData and am wondering if this maybe a bit overkill for what i need. I don't need to mirror the whole DB or anything like that.
Can I constructively use NSUserDefaults to store this king of information.
What are NSUserDefaults limitations in terms of what types you can store and how much.
The off line version will possibly need to store more entities than just the above so is it a viable method of storing data providing the amount of data is't massive.
Any advice would be great.
NSUserDefaults
NSUserDefaults is really meant for storing small pieces of data such as settings, preferences, and individual values.
NSUserDefaults offers a trivial learning curve and thread safe implementation.
CoreData
Learning curve may be a bit steep
CoreData and related classes provide easy ways to get your entities into UITableViews, like NSFetchedResultsController.
CoreData abstracts away a lot of the messy things you'd otherwise have to deal with yourself, such as lists of objects, one-to-many or many-to-many relationships, or constraints on object attributes, into a single nice clean object-oriented interface
CoreData manages save and undo functionality for you. It has a persistent store, which tracks changes, and can be flushed to the disk automatically at any number of times
However, if you're new to Cocoa I would avoid CoreData, to give yourself a chance to learn the basics first.
If I had to choose I would dive directly into CoreData. It makes sense also for small projects. NSUserDefaults is not meant to be used as a database (all the operations are ran on the main thread).
Coredata may be an overkill at first, but as your app grows so does your datamodel. CoreData is designed for such changes.
NSUserDefaults will store anything as long as the object complies to the NSCoding protocol, but its not meant to store a lot of information. Besides that, it can be difficult to fetch the data in NSUserDefaults, while it is rather easy in CoreData. Also note that relations between objects are unmanageable when storing objects in NSUserDefaults.

What are the pros and cons of using multiple NSPersistentStores for a single model?

Let's say I have a single model but I want to save objects to more than 1 NSPersistentStores. Assuming I use a single NSPersistentStoreCoordinator to manage those stores, what are the pros and cons of this setup?
With regard to the original question (multiple stores, one coordinator):
The potential advantage of two stores under one PSC is that you can spread out the data between two sqlite files (assuming that's the store type you're using). This can be helpful for example if you want to ship a pre-populated sqlite file with your app (which you can easily update in subsequent releases by shipping a new file), while still having user-created data next to it.
The disadvantage is that handling relationships across different stores is more cumbersome than within one store.
With regard to another answer to this question (multiple coordinators):
There certainly are potential benefits of using multiple coordinators with the same store, primarily performance related. Any request to the coordinator will lock it, so that everybody else has to wait to fetch data or save data. By using two coordinators you can push the lock down to the sqlite file, where it comes and goes much quicker.
Furthermore, a sqlite store that uses write-ahead-logging instead of a rollback journal enables multiple reader, single writer access to the store. By using two coordinators you can take advantage of sqlite's concurrency abilities. Apple is using this pattern internally too.
See also Apple's WWDC 2013 session on Core Data and iCloud (can't link because of ongoing dev-center outage...)
But keep in mind that all this is pretty esoteric and not necessary in almost all cases.

Keeping Core Data Objects in multiple stores

I'm developing an iOS application using Core Data. I want to have the persistent store located in a shared location, such as a network drive, so that multiple users can work on the data (at different times i.e. concurrency is not part of the question).
But I also want to offer the ability to work on the data "offline", i.e. by keeping a local persistent store on the iPad. So far, I read that I could do this to some degree by using the persistent store coordinator's migration function, but this seems to imply the old store is then invalidated. Furthermore, I don't necessarily want to move the complete store "offline", but just a part of it: going with the simple "company department" example that Apple offers, I want users to be able to check out one department, along with all the employees associated with that department (and all the attributes associated with each employee). Then, the users can work on the department data locally on their iPad and, some time later, synchronize those changes back to the server's persistent store.
So, what I need is to copy a core data object from one store to another, along with all objects referenced through relationships. And this copy process needs to also ensure that if an object already exists in the target persistent store, that it's overwritten rather than a new object added to the store (I am already giving each object a UID for another reason, so I might be able to re-use the UID).
From all I've seen so far, it looks like there is no simple way to synchronize or copy Core Data persistent stores, is that a fair assessment?
So would I really need to write a piece of code that does the following:
retrieve object "A" through a MOC
retrieve all objects, across all entities, that have a relationship to object "A"
instantiate a new MOC for the target persistent store
for each object retrieved, check the target store if the object exists
if the object exists, overwrite it with the attributes from the object retrieved in steps 1 & 2
if the object doesn't exist, create it and set all attributes as per object retrieved in steps 1 & 2
While it's not the most complicated thing in the world to do, I would've still thought that this requirement for "online / offline editing" is common enough for some standard functionality be available for synchronizing parts of persistent stores?
Your point of views greatly appreciated,
thanks,
da_h-man
I was just half-kidding with the comment above. You really are describing a pretty hard problem - it's very difficult to nail this sort of synchronization, and there's seldom, in any development environment, going to be a turn-key solution that will "just work". I think your pseudo-code description above is a pretty accurate description of what you'll need to do. Although some of the work of traversing the relationships and checking for existing objects can be generalized, you're talking about some potentially complicated exception handling situations - for example, if updating an object, and only 1 out 5 related objects is somehow out of date, do you throw away the update or apply part of it? You say "concurrency" is not a part of the question, but if multiple users can "check out" objects at the same time, unless you plan to have a locking mechanism on those, you would start having conflicts when trying to make updates.
Something to check into are the new features in Core Data for leveraging iCloud - I doubt that's going to help with your problem, but it's generally related.
Since you want to be out on the network with your data, another thing to consider is whether Core Data is the right fit to your problem in general. Since Core Data is very much a technology designed to support the UI and MVC pattern in general, if your data needs are not especially bound to the UI, you might consider another type of DB solution.
If you are in fact leveraging Core Data in significant ways beyond just modeling, in terms of driving your UI, and you want to stick with it, I think you are correct in your analysis: you're going to have to roll your own solution. I think it will be a non-trivial thing to build and test.
An option to consider is CouchDB and an iOS implementation called TouchDB. It would mean adopting more of a document-oriented (JSON) approach to your problem, which may in fact be suitable, based on what you've described.
From what I've seen so far, I reckon the best approach is RestKit. It offers a Core Data wrapper that uses JSON to move data between remote and local stores. I haven't fully tried it yet, but from what the documentation reads, it sounds quite powerful and ideally suited for my needs.
You definetly should check these things:
Parse.com - cloud based data store
PFIncrementalStore https://github.com/sbonami/PFIncrementalStore - subclass of NSIncrementalStore which allows your Persistent Store Coordinator to store data both locally and remotely (on Parse Cloud) at the same time
All this stuff are well-documented. Also Parse.com is going to release iOS local datastore SDK http://blog.parse.com/2014/04/30/take-your-app-offline-with-parse-local-datastore/ wich is going to help keep your data synced.

Resources