Search code examples
iosswiftrealmxcode9

mmap() failed: Cannot allocate memory size: 268435456 offset: 2684354560 on RealmSwift 2.10.2


My realm was growing up so much so I have an exception for memory allocation size. My realm size is about 3.2 GB so I put this realm's configuration to resolve this:

let config = Realm.Configuration(
        // Set the new schema version. This must be greater than the previously used
        // version (if you've never set a schema version before, the version is 0).
        schemaVersion: 11,

        // Set the block which will be called automatically when opening a Realm with
        // a schema version lower than the one set above
        migrationBlock: { migration, oldSchemaVersion in

    },shouldCompactOnLaunch: {totalBytes, usedBytes -> Bool in
        guard totalBytes > 10 * 1024 * 1024 * 1024 else { return false }
        guard Double(usedBytes) / Double(totalBytes) < 0.5 else { return false }
        print("Should compact Realm database: \(usedBytes) / \(totalBytes)")
        return true

    })

Realm.Configuration.defaultConfiguration = config

However, the issue still occurs. What am I doing wrong?

Regards


Solution

  • My guess goes for that you are missing the autoreleasepool in your dispatch async methods.

    The documentation shows that you should do that though.

    // Query and update from any thread
    DispatchQueue(label: "background").async {
        autoreleasepool { // <-- !!!
            let realm = try! Realm()
            let theDog = realm.objects(Dog.self).filter("age == 1").first
            try! realm.write {
                theDog!.age = 3
            }
        }
    }
    

    Another possibility of course is that you're inserting about 100000 objects many times without cutting them into batches of ~1000.

    Another possibility is inserting every single item in its own transaction.

    So like, super-large transactions can allocate a lot of space, but inserting each item one by one takes up lots of space too, hence the middle-ground.