Challenges/Problems In Real Application(RealmSwift Part 8)
In this blog I will cover the possible challenges or problems you can face while using realm in real application. It is mandatory that you went through all previous parts if that was not the case then this is not for you.
Migration Problems and Challenges
For the section it is mandatory that you read part 6
While doing heavy custom migration make sure migration code don’t trigger from application:didFinishLaunchingWithOptions,
Meet the watchdog
applicationDidBecomeActive,applicationDidEnterBackground,applicationWillResignActive or applicationWillTerminate?.
iOS’ watchdog process generates a “watchdog timeout = 20sec” when an app takes too long to launch, terminate, or respond to system events. Note that this is not an application crash, but an app “kill” by iOS itself. App “kills” cannot be reported by 3rd-party crash reporting solutions even though there is an underlying exception. From Apple’s Tech Note 2151[7]:
The exception code 0x8badf00d indicates that an application has been terminated by iOS because a watchdog timeout occurred. The application took too long to launch, terminate, or respond to system events. One common cause of this is doing synchronous networking on the main thread. Whatever operation is on Thread 0 needs to be moved to a background thread, or processed differently, so that it does not block the main thread.
Let’s understand it. As shown in Figure 1 we have a model and we saved lots of the object and make its size to 5mb
as shown in Figure 2
Now our model has change we need to do some custom migration as shown in Figure 3 where we are assigning some hard coded value to our previous data to incorporate new model changes
We created a schema version from 1 to 2 to tell realm there is a difference in a schema don't crash
As shown in Figure 5 it takes 9 seconds to return didFinish
method what if takes more than that watchdog
will kill your application
As shown in Figure 6 by accessing the reference of realm object it will trigger the migration
Solution 1: As shown in Figure 7 we reduced the didFinishLaunching
time by accessing realm instance after application launched in viewDidLoad
of the controller
Solution 2: Also you can create a screen which will be the default screen for your app and upon this screen use code for custom migration and show an activity to user to wait for the completion after application launch
Solution 3: If you really want migration in didfinishlaunching
, you can dispatch it in new thread
Don’t Do this
Don’t change thread on migration code. If you do the migration will not happen because of the mismatch of the thread . Feel free to correct me if this is not the case
Realm Notifications
For the section it is mandatory that you read part 2.
Rule of Thumb
Don’t observe Realm object that is not persisted into the database otherwise application will crash. In next part we will discuss this in detail