for example in the case:
@NSManaged public var myProperty: SomeType
func someFunc() {
concurrentNSManagedObjectContext.perform {
doSomething(with: self.myProperty)
}
}
and what is the best practices, if yes?
for example in the case:
@NSManaged public var myProperty: SomeType
func someFunc() {
concurrentNSManagedObjectContext.perform {
doSomething(with: self.myProperty)
}
}
and what is the best practices, if yes?
SeaSpell
On
"Thread safety" at least in Apple Platforms thus far resolves to two things; reading, and writing. NSManaged object currently does not protect against a mix of the two. func doSomething(...) is going to throw an exception if some other thread is reading myProperty at time of mutation. Mutation can be done on a serial thread, however thread safety is more complicated than that. someFunc() is called by the first caller; if that caller is coming from a concurrent thread there is no guarantee of the order. If for example myProperty is of type Int and I call someFunc concurrent from 200 threads, the last thread may be 0 and someFunc may be += 1. Now if I make the func serial my end output is 1. So the short answer is it depends on what you're trying to accomplish. generally you are safe on a serial queue, but concurrent takes a lot of planning.
Copyright © 2021 Jogjafile Inc.
Using
@NSManagedhas no effect on thread safety. It helps Core Data manage the property but doesn't do anything about keeping the property safe for threads or anything else.Using
performas you are is good if thedoSomethingfunction relates to Core Data, becauseperformandperformAndWaitare how Core Data manages thread safety. Accessing the property insideperformorperformAndWaitis safe; accessing it outside of those functions is usually not safe.The only exception to the above is that if your managed object context uses main-queue concurrency (for example if you're using
NSPersistentContainerand the context is theviewContextproperty) and you're sure that your code is running on the main queue, then you don't need to useperformorperformAndWait. It's not bad to use them in that case but it's not necessary either.