0

I am getting an exception when I filter and try to delete records from Realm DB. It appears that the records are being deleted. The do / catch however is not responding as I expected. What am I doing wrong?

func deleteRecords (module: String, version:String, workorder: String) {
    let realm = try! Realm()
    let predicate = NSPredicate(format: "module = %@ && version = %@ && workorder = %@" , module, version, workorder)
    let results = realm.objects(NewRecord.self).filter(predicate)
    print("FILTERED: \(results.count) \(results)")

    do {
        try? realm.write {
            for result in results {
                print("DELETING: \(result)")
                realm.delete(result)
            }
        }
    } catch {
        // Catch anything that the above catches didn't catch
        print("ERROR THROWN DELETONG")
    }

}

The output looks like so:

FILTERED: 2 Results<NewRecord> <0x7f9cb1d27950> (
    [0] NewRecord {
        id = eaAerator008quantityWRK-000001;
        module = eaAerator;
        workorder = WRK-000001;
        version = 008;
        field = quantity;
        measure = None;
        valueString = 200;
        valueData = < — 0 total bytes>;
        diStatus = INSTALLED;
    },
    [1] NewRecord {
        id = eaAerator008installedQuantityWRK-000001;
        module = eaAerator;
        workorder = WRK-000001;
        version = 008;
        field = installedQuantity;
        measure = None;
        valueString = 150;
        valueData = < — 0 total bytes>;
        diStatus = INSTALLED;
    }
)
DELETING: NewRecord {
    id = eaAerator008quantityWRK-000001;
    module = eaAerator;
    workorder = WRK-000001;
    version = 008;
    field = quantity;
    measure = None;
    valueString = 200;
    valueData = < — 0 total bytes>;
    diStatus = INSTALLED;
}
DELETING: NewRecord {
    id = eaAerator008installedQuantityWRK-000001;
    module = eaAerator;
    workorder = WRK-000001;
    version = 008;
    field = installedQuantity;
    measure = None;
    valueString = 150;
    valueData = < — 0 total bytes>;
    diStatus = INSTALLED;
}

2017-08-13 23:05:07.982 DSMTracker[925:147376108] *** Terminating app due to uncaught exception 'RLMException', reason: 'Object has been deleted or invalidated.'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000107bbab0b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x0000000106d03141 objc_exception_throw + 48
    2   Realm                               0x00000001055eccf3 _ZL17RLMVerifyAttachedP13RLMObjectBase + 83
    3   Realm                               0x00000001055ee94c _ZN12_GLOBAL__N_18getBoxedIN5realm10StringDataEEEP11objc_objectP13RLMObjectBasem + 28
    4   Realm                               0x00000001055ee927 ___ZN12_GLOBAL__N_115makeBoxedGetterIN5realm10StringDataEEEP11objc_objectm_block_invoke + 39
    5   DSMTracker                          0x00000001044bdfb9 _TFC10DSMTracker23DirectInstallController9tableViewfTCSo11UITableView6commitOSC27UITableViewCellEditingStyle8forRowAtV10Foundation9IndexPath_T_ + 841
    6   DSMTracker                          0x00000001044be0af _TToFC10DSMTracker23DirectInstallController9tableViewfTCSo11UITableView6commitOSC27UITableViewCellEditingStyle8forRowAtV10Foundation9IndexPath_T_ + 95
    7   UIKit                               0x000000010942ec8c -[UITableView _animateDeletionOfRowWithCell:] + 172
    8   UIKit                               0x0000000109404289 __52-[UITableView _swipeActionButtonsForRowAtIndexPath:]_block_invoke + 84
    9   UIKit                               0x0000000109430334 -[UITableView _actionButton:pushedInCell:] + 212
    10  UIKit                               0x0000000109690d75 -[UITableViewCell _actionButtonPushed:] + 82
    11  UIKit                               0x00000001092c1d22 -[UIApplication sendAction:to:from:forEvent:] + 83
    12  UIKit                               0x000000010944625c -[UIControl sendAction:to:forEvent:] + 67
    13  UIKit                               0x0000000109446577 -[UIControl _sendActionsForEvents:withEvent:] + 450
    14  UIKit                               0x00000001094454b2 -[UIControl touchesEnded:withEvent:] + 618
    15  UIKit                               0x00000001097eaea9 _UIGestureEnvironmentSortAndSendDelayedTouches + 5553
    16  UIKit                               0x00000001097e5ec0 _UIGestureEnvironmentUpdate + 1409
    17  UIKit                               0x00000001097e58f3 -[UIGestureEnvironment _deliverEvent:toGestureRecognizers:usingBlock:] + 484
    18  UIKit                               0x00000001097e4aba -[UIGestureEnvironment _updateGesturesForEvent:window:] + 274
    19  UIKit                               0x0000000109330b9a -[UIWindow sendEvent:] + 4092
    20  UIKit                               0x00000001092dd7b0 -[UIApplication sendEvent:] + 352
    21  UIKit                               0x0000000109ac0adc __dispatchPreprocessedEventFromEventQueue + 2926
    22  UIKit                               0x0000000109ab8a3a __handleEventQueue + 1122
    23  CoreFoundation                      0x0000000107b60c01 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    24  CoreFoundation                      0x0000000107b460cf __CFRunLoopDoSources0 + 527
    25  CoreFoundation                      0x0000000107b455ff __CFRunLoopRun + 911
    26  CoreFoundation                      0x0000000107b45016 CFRunLoopRunSpecific + 406
    27  GraphicsServices                    0x0000000110337a24 GSEventRunModal + 62
    28  UIKit                               0x00000001092c00d4 UIApplicationMain + 159
    29  DSMTracker                          0x00000001048cad27 main + 55
    30  libdyld.dylib                       0x000000010ca6d65d start + 1
    31  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
bdash
  • 18,110
  • 1
  • 59
  • 91
Syed Tariq
  • 2,878
  • 3
  • 27
  • 37
  • try change your `try?` to `try` and `catch` to `catch let error as NSError` and print the error – Tj3n Aug 14 '17 at 05:05
  • 1
    Possible duplicate of [Realm object has been deleted or invalidated](https://stackoverflow.com/questions/31852782/realm-object-has-been-deleted-or-invalidated) – Tj3n Aug 14 '17 at 05:10
  • Moreover, you should not write elements of a collection to Realm one-by-one, since a write transaction has a significant overhead, so you should try to minimise the number of write transactions. Realm supports adding a homogenous array using a single write transaction, so you should use this. – Dávid Pásztor Aug 14 '17 at 09:07
  • It looks from the backtrace like the exception you're seeing is being thrown after `deleteRecords` has returned. Can you share what the crashing function (`DirectInstallController.tableView(commit:forRowAt:)`) is doing? Based on the exception you're seeing it seems likely that it's accessing a reference to one of the object's you've just deleted. It's deleted, so it's no longer valid to access it. – bdash Aug 14 '17 at 22:35

0 Answers0