Potential problems with link counting if you don't capture a fresh link in the background thread

I have a second question after reading Marcus S. Zarra (excellent) Basic data: Data storage and management for iOS, OS X and iCloud (2nd edition), if possible.

The section of the book Asynchronous Adding NSPersistentStore contains this code fragment (excerpt):

dispatch_queue_t queue; queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(queue, ^{ // ... NSPersistentStoreCoordinator *coordinator = nil; coordinator = [[self managedObjectContext] persistentStoreCoordinator]; // ... }); 

It also contains the following explanation:

The reason we get a new link to the NSPersistentStoreCoordinator is one of the security aspects. If we used links from an external method, we would increase the NSPersistentStoreCoordinator counter NSPersistentStoreCoordinator and a potentially unnecessary problem with link counting.

What is the nature of this potential link count problem?

I understand that if the block sent referred to the NSPersistentStoreCoordinator , which would be limited externally, it would retain this coordinator (by increasing the number of links per unit), which can then be released only after the blocks have completed execution. If the background thread has never been executed or if it has not completed, the problem with reference counting will remain.

Is this all there is, or are there more subtle cases that will also constitute problems with link counting and which may arise in this situation?

Be that as it may, I would not (seriously) be concerned about the potential problem of link counting in this particular case (a simple operation that is sent for immediate execution), but maybe I am missing something.

0
source share
1 answer

The block itself can be executed relatively late in this example (a lot of other code can be executed before this block). This means that a lot can happen with the context or the store coordinator, and hypothetically the store coordinator is not even the same object before and after the start of the block.

By calling the dispatcher to get a new link for the coordinator, you first make sure that you get the last coordinator, and also save the current coordinator, not freed from the block. If you intend to reuse the coordinator from outside the block, the coordinator will be saved and may produce (albeit unlikely) problems, such as bloating memory. And if everything goes wrong, and the block is never executed, the coordinator simply remains forever, and you have a memory leak.

This is just good practice.

0
source

Source: https://habr.com/ru/post/1214906/


All Articles