CoreData - saving part of context - ios

Please, can someone help me with problem i have.
I use singleton object for operations with Core Data. I want to be able to create an object and save it, but I don't want to save whole context, just newly created object. And I want that data to be seen right away.
Many people had problems with nested contexts, so I guessed it would be better if I used multiple persistent stores with same context, correct me if I'm wrong.
So, is having many stores and just switching between them the right way to save certain objects?

Related

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.

What is the preferred way to architect functions with coredata?

There is no shortage of tutorials on coredata, or questions here on SO about how to get started with coredata, or how to use specific parts.
My question is higher level - how should a larger project be architected with coredata?
Should the project keep most of the functions that deal with managed
objects in a single class?
Should the functions that deal with the
methods be static (I suppose they are called 'class methods') or
instance methods?
Is it ok to pass managed objects into class
methods from different threads? what about if I also supply a
context to the method?
Should I only be doing a single fetch for each entity when the app starts, then doing all of my searches and inserts against the context, or grabbing smaller sets of data from a fetch request as I need it?
As far as the blogosphere goes, it seems like the coredata architectures are the wild west - every man for themselves. Any good design patterns here to follow?
True, although some of you questions are really based on personal preference. I for one will never use a sigleton.
NO and YES. Yes on class to keep the connection to the context and no every controller will request its own data.
Using class methods requires you to either pass the context around or store it in a static. Using a static can cause problems if you need to change the context.
No, each thread should have it's now context. Core Data is not thread save.
To save memory only fetch what is needed, no sense in fetching everything at once.
I would suggest using NSFecthResultsController for filling things like table views.
If you are fetching data and storing it in core data I can really suggest using a separate context for inserting. Cocoanetics has a great article about multiple context setup.

Multiple Persistent Store Coordinator Core Data

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.

Stuck with Core Data object graph Handling

I'm having an object graph which contains several entities. i'm facing a situation where one entity can change several times but i need a way to revert it to the original state. Using some kind of undo/redo will probably not work well since other entities could change as well but i dont want to revert them.
I was thinking to just insert the changed object "naked" without any relationships. So the original one will stay in the object Graph and the changes will be floating alone.
Another way would be to change my Model so the object would be an Array. Within this i could save both and add some kind of identifier to recognize the appropriate object. However sometimes i need to replace the whole Graph and then i need to merge the changes.
I really feeling stuck with this Problem. Any help is appreciated.

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