aimelda
aimelda

Reputation: 13

Is the @NSManaged property thread safe?

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?

Upvotes: 1

Views: 65

Answers (2)

Tom Harrington
Tom Harrington

Reputation: 70946

Using @NSManaged has 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 perform as you are is good if the doSomething function relates to Core Data, because perform and performAndWait are how Core Data manages thread safety. Accessing the property inside perform or performAndWait is 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 NSPersistentContainer and the context is the viewContext property) and you're sure that your code is running on the main queue, then you don't need to use perform or performAndWait. It's not bad to use them in that case but it's not necessary either.

Upvotes: 1

SeaSpell
SeaSpell

Reputation: 758

"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.

Upvotes: 0

Related Questions