CoreData in main thread is common? - core-data

I worked with coreData some times, and I never search anything about this until import a lot of information.
CoreData by default using mainThread to create, update, delete and querying entities?
If yes, is a common scenario or is better use another thread to do this?

Yes it is common to use CoreData from the main thread. But it depends on your application's needs. If your application has some heavy CoreData work or needs to load the data in the background in order to make the UI more responsive, you can do it with multithreading but you will need to follow apple's guidelines.
You can find the apple's guide for Concurrency in NSManagedObjectContext here.

Related

Swift 3 Core Data relation does not delete related objects

I am writing a program using Xcode 8.3.3 and Swift 3.1 for iOS 10.3 (So I can use NSPersistentContainer with default Core Data Stack). I want to write very simple Core Data model with relationship. Problem is I do not know how to work with relations. I want to make a simple relation one to many. I already know, how to add this relations on Core Data scheme, there is screenshot:
So, one chat can have a lot of messages, one message can have only one chat. Delete rules on both ends are set to Cascade. I have my own class to work with Core Data objects (I am not generating it). Also, I have made manual models to each entity. But, when I am deleting chat, messages, associated with this chat, are not deleting. Question is: what should I do to force this relation work in proper way? And, why it is not deleting anything automatically?
Thank you for any help.
Relations in Core Data do not work automatically. I have to understand how to use them properly.

Alternative to Akka for handling tasks sequentially

I have a system which may generate certain events in the lifecycle of a transaction. On every even I need to update a row in a DB and also send out a UI event over websocket.
One option I have is to implement the event processing (DB and UI) in actors thus avoiding any locking issues - also I can afford minor delays so handling this sequentially will greatly simplify matters.
What are alternative ways of handling this in Scala as I feel maybe Actors might be overkill in this case?
There are those blogs stating that actors should be used for "concurrency with state" - though I would like to see a more appropriate mechanism in order to eliminate this option.
Ultimately the main unique benefit for using actors is that they are great for encapsulating mutable variables so that you avoid race conditions.
To do what you describe, you could just use classic threads. In your (possibly simplified) description, I don't see the potential for deadlocks. If you want to something a bit more composable, e.g. a sequence of asynchronous tasks, you can use Scala's Futures.
Not at all sure if this is applicable for Scala, but there's a great lib for Groovy and Java with several concurrency models. I've myself used the Dataflow Concurrency with great success and can recommend it as a light-weight yet manageable model.
Dataflow Concurrency offers an alternative concurrency model, which is
inherently safe and robust. It puts an emphasis on the data and their
flow though your processes instead of the actual processes that
manipulate the data. Dataflow algorithms relieve developers from
dealing with live-locks, race-conditions and make dead-locks
deterministic and thus 100% reproducible. If you don’t get dead-locks
in tests you won’t get them in production.
There are other models available in the linked GPars library as well.
I wouldn't suggest making the threading yourself, unless you have no other choices.
Addendum
After posting I got interested in the topic and made a few searches. Seems like Akka has direct support for Dataflow model also. Or at least has had in some version.
Actors avoid locking issues because they use queues to interact. You can use threads with (blocking) queues and get the same level of safety. The only advantage of Actors over Threads is that an Actor does not spend memory for call stack, thus we can have many more actors than threads in the same amount of core memory. The downside of actor model is that a complex algorithm which could be implemented in single thread require several actors and so actor implementation may look obscured.

ViewModel and multithreading best practice

I want to understand some best practices regarding using MVVM and multithreading. Let us assume I have a ViewModel and it has an observableCollection. Also, let us assume I pass this collection to another service class which does some calculation and then udpates my collection.
After a point I realize that I want to make this a multithreaded call. When I make the call to the service class using threads or tasks what results is a cross thread operation. The reason is quite obvious because the service class updates the collection whcih in turn will update the UI on the background thread.
In such scenarios what is the best practice? Should we always write our service class in such a way that it first clones the input and then updates that cloned copy? Or should the view model always assuem that the service calls might be multithreaded and send a cloned copy?
What would be the recommended way to solve this?
Thanks
Jithu
A solution that might solve the cross-thread exception is by implementing the OnPropertyChanged in the base class of all ViewModels to switch to the correct thread/synchronization context so all properties in the View that are bound to the changing property will have their handlers called on the correct thread. See: Avoid calling BeginInvoke() from ViewModel objects in multi-threaded c# MVVM application
If/when you create copies you are postponing the synchronization and, in many cases, making it harder than need be.
A web service will always return new objects, how you, or a framework, updates the model using these object is up to you. A lot would depend on the amount of checks and updates coming in. There is no recommended way, see whatever fits the applications requirements.

Trying to identify a design pattern

I am currently working with an inherited piece of code that uses a very interesting design pattern.
The code is split into a number of objects. I am not sure if the term object is applicable since it is a C code, but it is the best analogy. Each object has object-specific data, a thread, and a message queue. All objects primarily communicate by placing pre-defined messages onto each-other's queues. The main idea seems to be is that each object's data is only accessed by one thread. After doing some research I discovered that a few industrial automation applications are written this way (namely the ProfiNET stack and some EIP implementations).
Do you know if this pattern has a name or if it is describes somewhere in the literature? The "Pattern-Oriented Software Architecture" book by Schidt, Stal, et al does not mention it.
Thank you very much.
This sounds somewhat related to the Actor model.
It might be me but is any other pattern except producer consumer combined with mutual exclusion used in what you described ?
Check out Communicating Sequential Processes (CSP)
CSP allows the description of systems in terms of component processes
that operate independently, and interact with each other solely
through message-passing communication
It is actually one of the core design concepts that the Go language is based upon for communicating between goroutines (concurrency).

Doubts About Core Data NSManagedObject Deep Copy

I have a situation where I must copy one NSManagedObject from the main context into an editing context. It sounds unnecessary to most people as I have seen in similar situations described in Stackoverflow but I looks like I need it.
In my app there are many views in a tab bar and every view handles different information that is related to the other views. I think I need multiple MOCs since the user may jump from tab to tab and leave unsaved changes in some tab but maybe it saves data in some other tab/view so if that happens the changes in the rest of the views are saved without user consent and in the worst case scenario makes the app crash.
For adding new information I got away by using an adding MOC and then merging changes in both MOCs but for editing is not that easy. I saw a similar situation here in Stackoverflow but the app crashes since my data model doesn't seem to use NSMutableSet for the relationships (I don't think I have a many-to-many relationship, just one-to-many) I think it can be modified so I can retrieve the relationships as if they were attributes
for (NSString *attr in relationships) {
[cloned setValue:[source valueForKey:attr] forKey:attr];
}
but I don't know how to merge the changes of the cloned and original objects. I think I could just delete the object from the main context, then merge both contexts and save changes in the main context but I don't know if is the right way to do it. I'm also concerned about database integrity since I'm not sure that the inverse relationships will keep the same reference to the cloned object as if it were the original one.
Can some one please enlighten me about this?
Wow, lots of questions and randomness in this one. First, you do not need to add comments to your own question, better to edit the question itself.
Second, you don't need multiple NSManagedObjectContext instances if you are running a single threaded application. Your entire application can easily run off of a single instance. Multiple contexts are for rare edge cases and multi-threading situations.
By using a single context it will resolve all of your issues with your attempts to clone. However, if you are still wondering how to do a deep copy of a NSManagedObject you can get some guidance from the example code in my book at The Pragmatic Programmers; the source code of which is free to download.
Update
All NSManagedObjectContext instances are "editing ones". You only need a single context per thread. You can easily ask the context for the non-inserted entities if you want to delete them before a save and you can easily save entities as they are changed. Except for some extreme edge cases you do not need a second context.
Update
You are still creating more work for yourself then you need to. You don't need to save an object for the view to go away. You can leave as many objects as you want in an unsaved state in the context.
You are going to spend more time debugging dealing a deep copy of objects than it is worth with the design you are describing. If you are going to use more than one context, make sure they are attached to the same NSPersistentStoreCoordinator so that you don't need to copy the objects around, you can just save the "secondary" context and then catch the save notification in the main context.

Resources