What is the correct way to use scope in autoreleasepool?

This is what the documentation has to say about access to the kingdom using GCD:

"You must use an explicit autostart pool when accessing the kingdom from the dispatch queue."

Documentation

I used this practice in my application, but suddenly I see the following message in the console: "The RLMRealm instance was released during the write transaction."

This is not a mistake, it just prints it to the console. Nothing is written to the database.

I found this problem on github which seems very similar.

Now my question is: what practice should I use? The one used in the Kingdom documentation or the answer found in the github issue?

Thanks for any clarification.

+6
source share
1 answer

GCD blocks manage their @autorelease pools, but there is no guarantee that this will actually happen, and this can happen for a sufficient amount of time after the block itself completes (see SO>

Realm supports reading locks in all of its instances by stream (so you can still read from Realm while the write transaction is open in another thread), so it was recommended that you explicitly exclude the Realm instance when you are finished, so that the disk space is corrected.

If you do not use @autoreleasepool , nothing bad will happen; only the size of the Realm file on disk will increase.

Best practice is to use the @autoreleasepool block and ensure that all of your write transactions are committed inside that block.

 @autoreleasepool { let realm = try! Realm() try! realm.write { // ... perform changes } } 

It is generally recommended that you use realm.write over beginWrite() / commitWrite() , since it allows you to safely execute transactions without forgetting to comment, and also provides additional error handling.

The problem with the GitHub problem was that there was a logical path due to which @autoreleasepool had to exit before the write transaction was completed. In this case, you need to look at your code logic and make sure that you have nothing of the kind.

+4
source

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


All Articles