What is meant by CoreData is not thread safe?

后端 未结 2 1847
死守一世寂寞
死守一世寂寞 2021-02-04 14:58

In Obj-C, what does it mean in simple terms; \"CoreData is not thread safe\"

OR in general what is \"not thread safe\" ?

2条回答
  •  渐次进展
    2021-02-04 15:49

    @d11wtq's answer is correct only when writing your own code or designing your own APIs.

    It is entirely incorrect when working with a set of APIs and quite specifically wrong when working with Core Data.

    In the context of working with Mac OS X and iOS, thread safety must always be considered in the context of working with the system APIs. Even using, say, an NSArray means that you are working with the system APIs.

    OR in general what is "not thread safe" ?

    A non-thread safe API is an API where you cannot interact with the API from multiple threads simultaneously. There may also be additional restrictions that most often involve the main thread. For example, almost all drawing operations must occur on the main thread on both Mac OS X and iOS.

    The Apple documentation assumes thread safety is the exceptional case. That is, an API is only thread safe if the documentation explicitly claims thread safety. If there is no mention of thread safety, you must assume that the API is not thread safe.

    In Obj-C, what does it mean in simple terms; "CoreData is not thread safe"

    That statement is not quite correct, but it is a safe assumption.

    In Core Data's case, the thread interaction behavior is extremely well documented.

    In short, parts of the API are thread safe (the store coordinator, for example) and parts are quite explicitly not thread safe. While the MOC provides lock and unlock methods, you can also use external locking. But don't. It will be less efficient and more fragile; significantly so. In general, don't use the internal locking either. CoreData is optimized around having a context per thread/queue.

    (Answer fixed based on TC's feedback. Thanks.)

提交回复
热议问题