iosswiftcore-dataconcurrencynsmanagedobject

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?


Solution

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