Realm object has been deleted or invalidated

IosSwiftRealm

Ios Problem Overview


When I start my app, I perform an API call to see whether there's new data available. The data is stored in my local Realm database, and some of it is displayed in the initial table view controller.

Once the API call is finished, I check if some conditions are met that require me to delete a bunch of the previous data from the database and then create new objects. However, when I delete the old data, my app crashes with the following exception:

2015-08-06 11:56:32.057 MSUapp[19754:172864] *** Terminating app due to uncaught exception 'RLMException', reason: 'Object has been deleted or invalidated.'
*** First throw call stack:
(
0   CoreFoundation                      0x000000010660cc65 __exceptionPreprocess + 165
1   libobjc.A.dylib                     0x00000001083bdbb7 objc_exception_throw + 45
2   Realm                               0x0000000105b78e95 _ZL17RLMVerifyAttachedP13RLMObjectBase + 85
3   Realm                               0x0000000105b7878d _ZL10RLMGetLinkP13RLMObjectBasemP8NSString + 29
4   Realm                               0x0000000105b7c23e ___ZL17RLMAccessorGetterP11RLMProperty15RLMAccessorCodeP8NSString_block_invoke_12 + 46
5   MSUapp                              0x0000000105764867 _TFFC6MSUapp29FavoriteLeaguesViewController18generateLeagueListFS0_FT_T_U_FTCS_6LeagueS1__Sb + 39
6   MSUapp                              0x00000001057648eb _TTRXFo_oC6MSUapp6LeagueoS0__dSb_XFo_iS0_iS0__dSb_ + 27
7   libswiftCore.dylib                  0x0000000108674ae2 _TFSs14_insertionSortUSs21MutableCollectionType_USs13GeneratorType__Ss22BidirectionalIndexType_Ss18_SignedIntegerType_Ss33_BuiltinIntegerLiteralConvertible____FTRQ_GVSs5RangeQQ_5Index_RFTQQQ_9Generator7ElementS7__Sb_T_ + 1570
8   libswiftCore.dylib                  0x0000000108676682 _TFSs14_introSortImplUSs21MutableCollectionType_USs13GeneratorType__Ss21RandomAccessIndexType_Ss18_SignedIntegerType_Ss33_BuiltinIntegerLiteralConvertible_Ss16SignedNumberType_S3_____FTRQ_GVSs5RangeQQ_5Index_RFTQQQ_9Generator7ElementS8__SbSi_T_ + 1250
9   libswiftCore.dylib                  0x0000000108676172 _TFSs10_introSortUSs21MutableCollectionType_USs13GeneratorType__Ss21RandomAccessIndexType_Ss18_SignedIntegerType_Ss33_BuiltinIntegerLiteralConvertible_Ss16SignedNumberType_S3_____FTRQ_GVSs5RangeQQ_5Index_FTQQQ_9Generator7ElementS8__Sb_T_ + 1058
10  libswiftCore.dylib                  0x00000001085ec947 _TFSs4sortUSs21MutableCollectionType_USs13GeneratorType__Ss21RandomAccessIndexType_Ss18_SignedIntegerType_Ss33_BuiltinIntegerLiteralConvertible_Ss16SignedNumberType_S3_____FTRQ_FTQQQ_9Generator7ElementS6__Sb_T_ + 471
11  libswiftCore.dylib                  0x00000001086a8d9e _TPA__TFFSa4sortU__FRGSaQ__FFTQ_Q__SbT_U_FRGVSs26UnsafeMutableBufferPointerQ__T_ + 222
12  libswiftCore.dylib                  0x00000001086a8e18 _TPA__TTRG0_R_XFo_lGVSs26UnsafeMutableBufferPointerq___dT__XFo_lGS_q___iT__42 + 56
13  libswiftCore.dylib                  0x00000001085f7fda _TFSa30withUnsafeMutableBufferPointerU__fRGSaQ__U__FFRGVSs26UnsafeMutableBufferPointerQd___Q_Q_ + 522
14  libswiftCore.dylib                  0x00000001085f7db4 _TFSa4sortU__fRGSaQ__FFTQ_Q__SbT_ + 132
15  MSUapp                              0x0000000105761709 _TFC6MSUapp29FavoriteLeaguesViewController18generateLeagueListfS0_FT_T_ + 1097
16  MSUapp                              0x000000010576354b _TFC6MSUapp29FavoriteLeaguesViewController27numberOfSectionsInTableViewfS0_FCSo11UITableViewSi + 59
17  MSUapp                              0x00000001057635fa _TToFC6MSUapp29FavoriteLeaguesViewController27numberOfSectionsInTableViewfS0_FCSo11UITableViewSi + 58
18  UIKit                               0x000000010737cac3 -[UITableViewRowData _updateNumSections] + 84
19  UIKit                               0x000000010737d4b4 -[UITableViewRowData invalidateAllSections] + 69
20  UIKit                               0x00000001071c873b -[UITableView _updateRowData] + 217
21  UIKit                               0x00000001071de2b7 -[UITableView noteNumberOfRowsChanged] + 112
22  UIKit                               0x00000001071dd9f5 -[UITableView reloadData] + 1355
23  MSUapp                              0x00000001057647c6 _TFFC6MSUapp29FavoriteLeaguesViewController11viewDidLoadFS0_FT_T_U_FTO10RealmSwift12NotificationCS1_5Realm_T_ + 166
24  RealmSwift                          0x0000000105f37210 _TFF10RealmSwift41rlmNotificationBlockFromNotificationBlockFFT12notificationOS_12Notification5realmCS_5Realm_T_bTSSCSo8RLMRealm_T_U_FTSSS2__T_ + 224
25  RealmSwift                          0x0000000105f372af _TTRXFo_oSSoCSo8RLMRealm_dT__XFdCb_dCSo8NSStringdS__dT__ + 111
26  Realm                               0x0000000105c0645a -[RLMRealm sendNotifications:] + 986
27  Realm                               0x0000000105c068e6 -[RLMRealm commitWriteTransaction] + 262
28  Realm                               0x0000000105c06a48 -[RLMRealm transactionWithBlock:] + 120
29  RealmSwift                          0x0000000105f34250 _TFC10RealmSwift5Realm5writefS0_FFT_T_T_ + 176
30  MSUapp                              0x00000001056d46db _TZFC6MSUapp14DatabaseHelper23removeForSportAndSeasonfMS0_FTCS_5Sport6seasonSS_T_ + 603
31  MSUapp                              0x0000000105710d22 _TFFFC6MSUapp11AppDelegate14loadRemoteDataFS0_FT_T_U_FGSaCS_5Sport_T_U_FGSaCS_6League_T_ + 866
32  MSUapp                              0x0000000105710dc7 _TTRXFo_oGSaC6MSUapp6League__dT__XFo_iGSaS0___iT__ + 23
33  MSUapp                              0x00000001057103d1 _TPA__TTRXFo_oGSaC6MSUapp6League__dT__XFo_iGSaS0___iT__ + 81
34  MSUapp                              0x000000010575de90 _TTRXFo_iGSaC6MSUapp6League__iT__XFo_oGSaS0___dT__ + 32
35  MSUapp                              0x000000010575ddeb _TFZFC6MSUapp9APIHelper11loadLeaguesFMS0_FTSi18shouldWriteToRealmSb10completionGSqFGSaCS_6League_T___T_U_FCSo6NSDataT_ + 2763
36  MSUapp                              0x00000001056f4a0e _TTSf2n_n_n_n_n_d_i_n_n_n___TFFC6MSUapp14JSONDataSource18loadRemoteJsonDataFS0_FTSSCS_19GETParameterBuilderFCSo6NSDataT__T_U_FTCSo12NSURLRequestGSqCSo17NSHTTPURLResponse_GSqS2__GSqCSo7NSError__T_ + 2302
37  MSUapp                              0x00000001056f2d59 _TPA__TTSf2n_n_n_n_n_d_i_n_n_n___TFFC6MSUapp14JSONDataSource18loadRemoteJsonDataFS0_FTSSCS_19GETParameterBuilderFCSo6NSDataT__T_U_FTCSo12NSURLRequestGSqCSo17NSHTTPURLResponse_GSqS2__GSqCSo7NSError__T_ + 249
38  Alamofire                           0x00000001059e7599 _TTRXFo_oCSo12NSURLRequestoGSqCSo17NSHTTPURLResponse_oGSqCSo6NSData_oGSqCSo7NSError__dT__XFo_oS_oGSqS0__iGSqS1__oGSqS2___dT__ + 25
39  Alamofire                           0x00000001059e7461 _TFFFC9Alamofire7Request8responseFDS0_US_18ResponseSerializer___FT5queueGSqCSo8NSObject_18responseSerializerQ_17completionHandlerFTCSo12NSURLRequestGSqCSo17NSHTTPURLResponse_GSqQ0__GSqCSo7NSError__T__DS0_U_FT_T_U_FT_T_ + 737
40  Alamofire                           0x00000001059e690e _TPA__TFFFC9Alamofire7Request8responseFDS0_US_18ResponseSerializer___FT5queueGSqCSo8NSObject_18responseSerializerQ_17completionHandlerFTCSo12NSURLRequestGSqCSo17NSHTTPURLResponse_GSqQ0__GSqCSo7NSError__T__DS0_U_FT_T_U_FT_T_ + 206
41  Alamofire                           0x00000001059a89d7 _TTRXFo__dT__XFdCb__dT__ + 39
42  libdispatch.dylib                   0x000000010938b186 _dispatch_call_block_and_release + 12
43  libdispatch.dylib                   0x00000001093aa614 _dispatch_client_callout + 8
44  libdispatch.dylib                   0x0000000109392a1c _dispatch_main_queue_callback_4CF + 1664
45  CoreFoundation                      0x00000001065741f9 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
46  CoreFoundation                      0x0000000106535dcb __CFRunLoopRun + 2043
47  CoreFoundation                      0x0000000106535366 CFRunLoopRunSpecific + 470
48  GraphicsServices                    0x000000010cc17a3e GSEventRunModal + 161
49  UIKit                               0x00000001070f08c0 UIApplicationMain + 1282
50  MSUapp                              0x000000010570f857 main + 135
51  libdyld.dylib                       0x00000001093df145 start + 1
52  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

This call stack lets me assume, that it's because of my write access in FavoriteLeaguesViewController's generateLeagueList method. The following is its body:

var favorites = FavoritesHelper.sharedInstance.favoriteLeagues
favorites.sort { $0.sport < $1.sport }

for favorite in favorites {
  // Add to array, which we can later use for cellForRowAtIndexPath
}

favorites is of the type [League], where League is a Realm Object. I'd assume the exception occurs because I'm accessing properties of the League objects, which have been deleted from the Realm database in the mean time (because the API call that has been started in the AppDelegate is now finished).

My question then is: How can I prevent this from happening? How can I make sure that there's no more writing/reading-access to any of the League objects prior to deleting them?

Ios Solutions


Solution 1 - Ios

You can check if an object has been deleted from the Realm by calling object.invalidated -- if it returns true, then it has been deleted or the Realm has manually invalidated.

Solution 2 - Ios

I got a really nice way to catch a RLMException within Swift.

Currently Swift doesn't show where a RLMException happened.

In Realm/RLMUtil.mm:266, there is the definition for RLMException.

If you change the code to generate a swift error,

Xcode now can show you where the exception occurred.

Now it is a part of Swift.

// Realm/RLMUtil.mm:266
static NSException *RLMException(NSString *reason, NSDictionary *additionalUserInfo) {
    // add some code to generate a swift error. E.g. division-by-zero.
    int a = 0;
    if (reason == nil) {
        a = 1;
    }
    NSLog(@"calculating 1 / %d = %f", a, 1 / a);

    ... remainder of the original code...
}

Solution 3 - Ios

I've just place breakpoint inside method:

// Realm/RLMUtil.mm:193
static NSException *RLMException(NSString *reason, NSDictionary *additionalUserInfo) {
    // ...
}

And on left panel you can check stack trace, here you can find where error throws.

Solution 4 - Ios

The issue was in my FavoritesHelper class. It had both a favoriteLeagueIDs and favoriteLeagues property. I always set both of them and used the IDs for internal usage and the other property for whenever I want some data from these leagues.

This meant, that all favorite leagues were constantly referenced by the favoriteLeagues property (of the type [League]), thus crashing the app when I wanted to fetch them after they're invalidated.

What I've done to fix this, was to change the property favoriteLeagues to a computed property as follows:

var favoriteLeagues: [League] {
	get {
        var leagues = [League]()
        for id in favoriteLeagueIDs {
            if let league = realm.objectForPrimaryKey(League.self, key: id) {
                leagues.append(league)
            }
        }
        return leagues
	}
}

Now the leagues are no longer referenced and just get loaded from the database when I need to read them. Invalidated or deleted objects don't get loaded because of the if let statement (the Realm.objectForPrimaryKey(:key:) method returns nil in such a case).

Solution 5 - Ios

I was unable to place breakpoints within the Realm framework itself as others suggested, but instead placed an exception breakpoint on my entire project:

enter image description here

This allowed me to catch a proper stack trace when the exception was thrown, and find my bug.

Solution 6 - Ios

you can calling isInvalidated or invalidated to judge the object is invalid (YES) or not (NO). you can also write a a custom method to define what is real invalidate

look for the document ,we will see a property:

 /**
 Indicates if the object can no longer be accessed because it is now invalid.

 An object can no longer be accessed if the object has been deleted from the Realm that manages it, or
 if `invalidate` is called on that Realm.
 */
@property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated;

the invalidated is readonly but what does isInvalidated mean?

it is equals to - (BOOL)invalidated { return invalidated; }

it means that you can write a a custom method to define what is real invalidate you want.

Solution 7 - Ios

Try to create the element on realm instead of add

So:

try! realm.write {
        realm.add(...)
    }

Replace with:

try! realm.write {
        realm.create(...)
    }

And then after the delete operation realm should work as expected!

Solution 8 - Ios

In my experience, if you trying to use target object (which you wanna delete) after delete, application will crash.

If you wanna trigger some code blocks after removing realm object, just trying to trigger that block right before the object removing in the memory. Trying to usage that object after removed from memory, will make some problem and will crash the app.

For example:

    try! realm.write {
        print("deleted word: \(targetObject.word)")
        realm.delete(targetObject)

        //  targetObject was removed, so don't try to access it otherwise you gonna got the 'nil' value instead of object.
    }

Solution 9 - Ios

In my case I was deleting data from 2 tables at once.. one with a foreign to the other.

        let itemToDelete = counters[indexPath.row]
        let realm = try! Realm()
        try! realm.write {
            realm.delete(itemToDelete)
            let predicate = NSPredicate(format: "counterid = \(c.id)")
            let children = realm.objects(Details.self).filter(predicate)
            realm.delete(children)
        }

But the problem was that I was trying to delete the children of the item that does not exist anymore. Switching the order, solved it!

        let itemToDelete = counters[indexPath.row]
        let realm = try! Realm()
        try! realm.write {
            let predicate = NSPredicate(format: "counterid = \(c.id)")
            let children = realm.objects(Details.self).filter(predicate)
            realm.delete(children)
            realm.delete(itemToDelete) //this should be deleted after
        }

Hope this helps someone else!

Solution 10 - Ios

Here are some of the reasons based on my past experiences.

  1. Overriding NSObject's isEqual(_ object: Any?), then returning identifier which was just deleted by Realm.

How did I fix it?

Check if object is invalidated if so return false otherwise proceed with using your identifier Example:

extension YourModel {
    override func isEqual(_ object: Any?) -> Bool {
        guard let object = object as? YourModel,
              !self.isInvalidated else {
            return false
        }
        return object.id == self.id
    }
}

Using Diffing tools

For those using diffing tools like RxDataSources, IGListKit etc.. you have to perform the same check as mentioned above before trying to access the indentifier.

Here is a work round if you are using RxDataSources that prevent the crash caused by adopting to IdentifiableType protocol.

Check if the Realm object was invalidated. If so, just return a random unique value, like so:

  var identity: String {
        return isInvalidated ? "deleted-object-\(UUID().uuidString)" : objectId
    }

Source: - https://github.com/RxSwiftCommunity/RxDataSources/issues/172#issuecomment-427675816

Solution 11 - Ios

after spent a day, i figure out with the remove DispatchQueue.main.async in my realm.delete() function and finally it worked.

DispatchQueue.main.async {
  realm.delete()
}

to

realm.delete()

Solution 12 - Ios

What you can do is observe the Results<> object returned from your initial Realm query (the one used to populate your list/table view) and update that list in the observer callback method whenever there is a change in the database.

Just make sure that you use the same Realm instance to delete/modify the object as the one used for the initial query.

EDIT:

Some code examples:

let realm = Realm()
let results = realm.objects(Favourite.self)
let notificationToken = results.observe { [weak self] (changes) in
    guard let tableView = self?.tableView else { return }
    tableView.reloadData()
}

// Somewhere else
try? realm.write {
    if let favourite = results.first {
         realm.delete(favourite)
    }
}

// OR
if let objectRealm = results.first?.realm {
    try? objectRealm.write {
        objectRealm.delete(results.first!)
    }
}

// Don't forget to stop observing in deinit{}
// notificationToken.invalidate()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpadaromView Question on Stackoverflow
Solution 1 - IossegiddinsView Answer on Stackoverflow
Solution 2 - Ioswjiee weofejView Answer on Stackoverflow
Solution 3 - IosNazarYavornytskyyView Answer on Stackoverflow
Solution 4 - IospadaromView Answer on Stackoverflow
Solution 5 - IosmarcelView Answer on Stackoverflow
Solution 6 - IosQun LiView Answer on Stackoverflow
Solution 7 - IosFabio CiurliaView Answer on Stackoverflow
Solution 8 - IosasilturkView Answer on Stackoverflow
Solution 9 - IosDany BalianView Answer on Stackoverflow
Solution 10 - IosMussa CharlesView Answer on Stackoverflow
Solution 11 - IosAli OzkaraView Answer on Stackoverflow
Solution 12 - IoskenView Answer on Stackoverflow