realm / realm-swift

Realm is a mobile database: a replacement for Core Data & SQLite
https://realm.io
Apache License 2.0
16.32k stars 2.15k forks source link

After 'realm.deleteAll()' This error occurred ➤ 'Object has been deleted or invalidated' #5888

Closed saeedmozaffari closed 6 years ago

saeedmozaffari commented 6 years ago

i have about 20 realm object class. after than i delete realm data and after than try for get object from database , realm return data to me but really not exist any data so when i want work with that returned object app will be crashed because not exist any data. so i got this error 'Object has been deleted or invalidated'"

in the other words

in my app after than user try for logout i user from following code for delete all realm objects value

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

after than i remove realm data when i try for get data from an object for example with the following code

if let userPrivacyInDb = IGDatabaseManager.shared.realm.objects(IGUserPrivacy.self).first {
try! IGDatabaseManager.shared.realm.write {
    switch igPrivacyType {
    case .avatar:
        userPrivacyInDb.avatar = igPrivacyLevel  // ***** Error Line  ➤➤➤  'Object has been deleted or invalidated'
    case .channelInvite:
        userPrivacyInDb.channelInvite = igPrivacyLevel
    case .groupInvite:
        userPrivacyInDb.groupInvite = igPrivacyLevel
    case .userStatus:
        userPrivacyInDb.userStatus = igPrivacyLevel
    case .voiceCalling:
        userPrivacyInDb.voiceCalling = igPrivacyLevel
    case .videoCalling:
        userPrivacyInDb.videoCalling = igPrivacyLevel
    case .screenSharing:
        userPrivacyInDb.screenSharing = igPrivacyLevel
    case .secretChat:
        userPrivacyInDb.secretChat = igPrivacyLevel
    }
}
}

realm will be return data !!! but really not exist any data in database!!! and now app will be crashed.

my app is open source. you can use it for reproduce this crash with logout and login again. App Source

Realm framework version: v3.6.0

Xcode version: v9.4.1

iOS/OSX version: 11

tgoyne commented 6 years ago

Beginning a write transaction will advance a Realm's local view of the data to reflect any changes made on different threads in the time since it was last refreshed. This means that if you are performing writes on multiple threads, any checks you do before starting a write transaction need to be repeated within the write transaction, as the state of your objects may have changed since you performed the checks. In this case, the object existed prior to advancing the version, but is deleted once the local view has been updated to reflect the deleteAll().

saeedmozaffari commented 6 years ago

@tgoyne thanks, that's solution was useful