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

App Crash on add(:_ update: true) method swift #5140

Closed saurabh-silicon closed 3 years ago

saurabh-silicon commented 7 years ago

Goals

I am saving the data to realm. It works fine. But When I delete data and save again app get crash. App is not crash all times when I a re-saving data. it crash once in 4-5 tries.

do {
      try! currentRealm.write({
        currentRealm.add(items, update: true)
      })
    }

When App crash Pointer takes me 'object_accessor.hpp' file. Below is code of object_accessor.hpp file. Pointer points where line starts with >>>> in below code.

template<typename ValueType, typename ContextType>
size_t Object::get_for_primary_key_impl(ContextType& ctx, Table const& table,
                                        const Property &primary_prop,
                                        ValueType primary_value) {
    bool is_null = ctx.is_null(primary_value);
    if (is_null && !primary_prop.is_nullable)
        throw std::logic_error("Invalid null value for non-nullable primary key.");
    if (primary_prop.type == PropertyType::String) {
>>>>        return table.find_first(primary_prop.table_column,
                                ctx.template unbox<StringData>(primary_value));
    }
    if (primary_prop.is_nullable)
        return table.find_first(primary_prop.table_column,
                                ctx.template unbox<util::Optional<int64_t>>(primary_value));
    return table.find_first(primary_prop.table_column,
                            ctx.template unbox<int64_t>(primary_value));
}

I am using Realm Swift 2.8.3 xcode 8.3.3 MacOs 10.12.5

Thanks

Expected Results

Actual Results

Steps to Reproduce

Code Sample

Version of Realm and Tooling

Realm framework version: ?

Realm Object Server version: ?

Xcode version: ?

iOS/OSX version: ?

Dependency manager + version: ?

austinzheng commented 7 years ago

Thanks for getting in touch with us. What is the error you are seeing when the app crashes? What sort of data are you passing into add(:_, update:), and what is your model class? A simple reproduction case that we could run to see this issue ourselves would be best. Thanks.

saurabh-silicon commented 7 years ago

When App crashes red pointer points to following line

return table.find_first(primary_prop.table_column, ctx.template unbox(primary_value));

on the right side it shows > Thread 17:EXC_BAD_ACCESS(code=1, address=0x54) I have also tried to print values passed in above line in console

(lldb) po primary_prop.type
String

(lldb) po primary_prop.table_column
nil

(lldb) po primary_value
fd405c97-beee-4d30-9a07-bb2258e1abb2-0000216d

I am passing Array(Dictionary<String, Item>) My Item Class is as below

import UIKit
import ObjectMapper
import RealmSwift
class Item: Object, Mappable {

  dynamic var id = ""
  dynamic var name: String? = nil
  dynamic var group: String = ""
  dynamic var category: String = ""

 override static func primaryKey() -> String? {
    return "id"
  }

  override class func indexedProperties() -> [String] {
    return ["name","group"]
  }

//Impl. of Mappable protocol
  required convenience init?(map: Map) {
    self.init()
  }

  //mapping function for object mapper
  func mapping(map: Map) {
    id <- map["_id"]
    name <- map["name"]
    group <- map["group"]
    category <- map["category"]
  }
}

App is NOT crashing everytime when I am deleting and resaving data. It happen sometimes.

austinzheng commented 7 years ago

It doesn't look like you are doing anything incorrectly. Unfortunately, it's not possible to troubleshoot this issue further based on the information you've provided. We can try building a reproduction case, but if you can provide one that would be even better.

saurabh-silicon commented 7 years ago

Thank you for your reply. As I told you App is not crashing everytime when I am resaving data. That's why I am not able to give you exact crash reproduction case. I have provided information which I have found. As I get exact reproduction case I will provide information to you. Thanks Again.

austinzheng commented 7 years ago

Thanks for the information you've provided. We don't require a repro case that always reproduces the problem, something that crashes once in a while is fine. We'll continue investigating as well.

rromanchuk commented 6 years ago

Hey guys, i can say I am getting this as well. I'm trying to come up with a reproducible case, but one thing i do notice that is similar to OP, is this happens after logging my user out, which I run

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

My usage is a bit more complicated being dispatched on a serial queue, but i believe i am following confinement/thread safety rules. Mine is throwing an EXC_BAD_ADDRESS exactly where @saurabh-silicon posted. This is shortly after the user logs back in and a main feed begins fetching again.

static func read(_ challengeID: String, page: Int = 1, failure: ((String) -> Void)? = nil, success: (() -> Void)? = nil) {
        let req = APIManager.shared.manager.request(MyAPI.readCheckIns(challengeID, page))
        APIManager.shared.call(req) { (data, statusCode) in

            switch statusCode {
            case .ok:
                checkinServiceQueue.async {
                    let realm = try! Realm()
                    realm.beginWrite()
                    let checkIns = Mapper<CheckIn>().mapArray(JSONArray: data as! [[String : Any]])
                    for checkIn in checkIns {
                        realm.add(checkIn, update: true)
                    }
                    do {
                        try realm.commitWrite()
                    } catch let error {
                        log.error(error)
                    }
                    DispatchQueue.main.async {
                        success?()
                    }
                }
                break
            default:
                failure?(C.ErrorMessages.generic)
                break
            }
        }
    }
roe commented 6 years ago

@rromanchuk did you ever resolve this? I have the same situation as you (user logs out, logs back in) and this exception consistently happens.

Some more detail as this is happening every time a user logs out and logs back in and it crashes the app:

rromanchuk commented 6 years ago

@roe I actually did solve this, funny enough I already forgot what it was. I posted the fix/problem somewhere on github, let me track it down. It was something simple/silly

rromanchuk commented 6 years ago

@roe found it https://github.com/realm/realm-cocoa/issues/4155#issuecomment-362871660

Similar to your steps, on user logout i call deleteAll() but it wasn't actually the problem. I was also cleaning up the users cache data, but didn't realize i was wiping out the realm file.

roe commented 6 years ago

Hah, I'm doing the exact same thing :) Thanks so much!