Multiple realms on concurrent background dispatch queue

Hi,

I’m working on an iOS application which needs to run multiple API requests concurrently and store their results to realm database.

So I’m using a OperationQueue which sends API requests concurrently (max 4) and then delegates their results to concurrent DispatchQueue. On this queue I always create a new Realm instance and write results to database.

The realm object has some raw data (strings and dates) and some relationships (either 1-1 or 1-many), so it also contains direct links to other realm objects or LinkingObjects.

At some point during the asynchronous writes I check one of the LinkingObjects count and I get a crash there which says:

Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x000001a1d093cb4d
VM Region Info: 0x1a1d093cb4d is not in any region. Bytes after previous region: 1783226420046
REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL
MALLOC_NANO 0000000280000000-00000002a0000000 [512.0M] rw-/rwx SM=PRV
—>
UNUSED SPACE AT END

Termination Signal: Segmentation fault: 11
Termination Reason: Namespace SIGNAL, Code 0xb
Terminating Process: exc handler [2158]
Triggered by Thread: 5

The code that crashes looks like this:

let realm = try Realm(configuration: config)
realm.write {
    // Creation/editing of new/existing object, assigning some base values and relationships

    var attachments = self.children.filter(...)

    guard attachments.count > 0 else {
        self.mainAttachment = nil
        return
    }

    let pdfs = attachments.filter(...).sorted(byKeyPath: "dateAdded", ascending: true)

    if pdfs.count > 0 {	// <- this count check crashes
        self.mainAttachment = pdfs.first
        return
    }

    // Other checks
    ...
}

So I wanted to ask whether the problem could be that I’m creating multiple Realm instances which then perform writes on a single concurrent DispatchQueue.

@Michal_Rentka Can you file an issue here with a reproduction case please: