I have just began learning Core data. When it comes to multithreading, some blogs say that in this case we should use children contexts (by creating a context and setting its parent) and just invoke the performBlock: method. However some other blogs say that we should avoid this approach since it has introduced many bugs.
I have just began developing an application that manipulates a large data base and the project manager voted for Core data (instead of SQLLite).
Could any one please give me some directions. Should i use the children contexts strategy (introduced since iOS 5) or is there a better way to perform multithreading with Core Data ?
Thanks.
Should i use the children contexts strategy (introduced since iOS 5)
or is there a better way to perform multithreading with Core Data ?
In addition to the concept you mentioned, Managed Object Contexts have built-in concurrency support without parent contexts (see https://developer.apple.com/library/ios/releasenotes/DataManagement/RN-CoreData/index.html).
If you create one using initWithConcurrencyType:, you can use performBlock: and performBlockAndWait: and the threading will be handled for you, assuming you follow the basic patterns outlined in the link above. The parent/child context approach can help you with synchronization.
There's also an NSOperation-based approach outlined here: http://www.objc.io/issue-2/common-background-practices.html. I personally wouldn't use it, because the built-in APIs are sufficient, but the article is very well written and should give you a good idea of what's going on.
How you implement this depends on the needs of your app.
some other blogs say that we should avoid this approach since it has
introduced many bugs.
I would ignore them, and focus on writing clean code for yourself. There are plenty of apps that use multithreading + Core Data without bugs.
Related
could someone tell me the main features that distinguish Magical Record from RESTKit?
They're both popular but they seem complementary, but I just need help in seeing what the relevant differences are. Is there a typical use case in which both frameworks are needed?
Thanks!
Magical Record is a wrapper around Core Data that gives you a number of higher level APIs that you can use to interact. This means you write less code to do common tasks.
RestKit is a wrapper around Core Data (or your basic model objects) and your RESTful interface to your server. RestKit can map your external data model to your internal data model and enact all of your server interaction. This means you write less code for interacting with the server and populating your model.
So, they aren't really comparable. You could look at using both together as they could be complementary.
I've done a fair amount of research over the past few days, but I'm not sure what the current best practice is for concurrent Core Data. The most relevant post seems to be this blog post, but in light of this analysis about the performance of different concurrency methods, it seems that the modern way with parent contexts might not be the best. Also, this example from Apple doesn't implement the best practice mentioned in Apple's own concurrency guide that recommends NOT using the default NSConfinementConcurrencyType.
In light of all of this, what is the simplest and best way to implement concurrency with Core Data? All I need is a background thread the do some long writes to Core Data without hanging up the UI. Code examples are appreciated.
As always, it really depend on what you are trying to accomplish.
"long writes" will hang your UI no matter the architecture you implement.
A write operation lock the DB file in the OS level and the sqlite engine level (if you use this kind of store), all pending read operations will have to wait for the write to end before they complete.
One of the most used optimisation methods is segmenting the database "load" process with multiple save operations (you shouldn't mind as this happen in the background).
So, to answer the question:
The simplest way for you, would probably be to use the architecture described in the blog post you mentioned (parent-child hierarchy). if you notice that this cause to much "stutter" for your UI, try to optimise your data load process or try a different architecture.
use instruments to find "bottle necks" in your application execution.
CodeData has "quirks"/bugs in every architecture that I know, and you will find them gradually, depending on your use of it.
My recommendation is to go with the parent/child context pattern. In the light of the sparse details you give (e.g. number of records, total volume of data, latency of delivery, etc). this seems to be the most flexible and proven solution that can also accommodate very large datasets.
Contrary to other claims, you can have a smoothly operating UI regardless of how long the "writes" are to your database. Obviously, that is what background threads are for. The mechanism to keep the UI fluid is through so-called notifications about data change. You can react to these gracefully without disturbing the user experience.
Your remark about NSConfinementConcurrencyType is correct. As stated in your source, it is there for backward compatibility, so you can just forget about it. Obviously, for concurrency you want to use NSPrivateQueueConcurrencyType when creating your context.
Where can I find concrete examples of advanced CoreData concurrency? By advanced I mean operations on contexts and NSManagedObjects that run simultaneously on two or more threads and every thread can both read and change objects. Each objects saves contexts and listen for changes in another threads, everyone merges changes properly, nothing crashes, there are no inconsistency exceptions, everything is done as it should be.
I read official Apple document about Core Data concurrency, now I'm looking for code examples, tutorials, books, or at least some more detailed information on how to handle this type of scenario.
there is a really nice blog post from cocoanetics:
Multi Context Core Data
and i have created a github repo for the Async Saving Example:
Multi Context Core Data GitHub
In learning about Core Data, I've noticed how (in Xcode's templates) Apple directly used the query classes inside the view controller. This seems like it is bad MVC (having database access logic directly inside the view controller). Would it make sense to abstract out these kinds of actions to a separate suite of classes that obtain the data from the database and pass it back to the view controller calling it?
EDIT–
So, just to be clear, when I say "kinds of actions", I specifically mean CRUD Operations. Though if you have ideas about other things that a so-called "Model-Controller" would do, I'd be interested in hearing about them.
It's a matter of opinion, and often yes the templates are the most simple form of working example. It's hard to have a template spin out multiple files, for example.
Yes, personally, I generally spin out a separate NSManagedObject subclass. I like to have a _MySubclass object that has all the auto-generated stuff, then have the model actually reference MySubclass which has model-based business logic (you can use mogenerator or other methods to do this too if so inclined). Perhaps thinking of it as "Model-Controllers" and "View-Controllers" is another way of putting it.
This is a very good question and the answer likely depends on your situation. Perhaps architecture purists would insist on separate Model controllers and there are a lot of benefits to this approach. However, sometimes I find myself using Key Values when I'm doing a simple view. When things are more complex, for example, when coding the same Model for the Mac and iOS, having separate Model Controllers will allow you to reuse a lot of code. When you must diverge, Obj C Categories are a very clean way to extend functionality without adding a lot of overhead. I personally favor categories over extensive subclassing.
Since NSFetchedResultsController was released, my model classes are leaner. There are a lot of nuances to this and experience will help you come up with the best solution for your App. I've also found that writing unit tests up front will help you force through issues and validate your design, or send you back to the drawing board :)
I am working on a asp.net mvc application.
I have a situation where I have to make many threads which are going to access the database using linqtosql. My question is, will it be fine to leave every thing on linqtosql to maintain the synchronization, because the threads will be accessing the database at the same time. Or I have to write my own code to do that.
If each thread is using its own database context, you will be fine. However, I don't believe the database context object is thread safe. So, it's best to make sure each thread has its own context.
Randy
I'm not sure what kind of synchronization you mean, but databases have been designed such that multiple clients (threads, processes, machines) can access/read/change data at the same time. Linq2Sql is - speaking very simply - just one of the mechanisms to emit SELECT/DELETE/UPDATE statements against the database.
If you are using ASP.NET MVC I would seriously take a look at using S#arp Architecture. It uses nHibernate but provides some scaffolding to make the data layer very easy to create and work with. It uses fluent nhibernate and the AutoPersistenceModel so there is no need to play with XML files for mappings. It also includes a number of very handy to have MVC tools.
Linq2SQL seems to have some pretty serious shortcomings whenever I've tried to do anything remotely sophisticated with it and I would probably only recommend it for very simple scenarios. Perhaps it's just me but I have observed some pretty ugly behaviour with L2S.