swift Realm在后台線程然后應用程序崩潰

[英]swift Realm in background thread then app is crash


It seems! I have tried everything but I cant able to do.

它似乎!我已經嘗試了一切,但我無法做到。

I am getting data from database in every 2 mint and post data in API.And my app stuck for some sec in every 2 mint. The reason is when I am getting data from the database that time app is stuck. I have to do in the background.

我每2薄荷從數據庫中獲取數據並在API中發布數據。我的應用程序每2分鍾就會停留幾秒鍾。原因是當我從數據庫獲取時間應用程序被卡住的數據時。我必須在后台做。

This is my code is working but the app is Stuck

這是我的代碼正在運行,但該應用程序是Stuck

 func getObjects(type: Object.Type) -> Results<Object>? {

            //... *****************************
            //...code is working but app is stuck 

            return realm.objects(type)
        }

 if let list = realm.getObjects(type: AssignedCalendars.self)?.filter("isRemove == \(true) AND isSynced == \(false)").toArray(ofType: AssignedCalendars.self) {
                if list.count > 0 {
                    list.forEach({ (calendar) in
                        let calendar_json = [APIKey.event_id : calendar.event_id, APIKey.offlineId: calendar.offlineId, APIKey.calendar_id: calendar.calendar_id.toArray(ofType: Int.self)] as [String: Any]
                        removedCalendars.append(calendar_json)
                    })
                }
                offlineRemovedCalendars.append(contentsOf: list)
                eventData[APIKey.calendar_removelist] = removedCalendars
            }

TRY 1 . TRY for run code in the background I have to try to use dispatch queue

嘗試1。 TRY在后台運行代碼我必須嘗試使用​​調度隊列

func getObjects(type: Object.Type) -> Results<Object>? {

            //... *****************************
            //...code is working but app is stuck 

            return realm.objects(type)
        }


 DispatchQueue.main.async(execute: {
        if let list = realm.getObjects(type: AssignedCalendars.self)?.filter("isRemove == \(true) AND isSynced == \(false)").toArray(ofType: AssignedCalendars.self) {

            DispatchQueue.global().async {
            if list.count > 0 {
                list.forEach({ (calendar) in
                    let calendar_json = [APIKey.event_id : calendar.event_id, APIKey.offlineId: calendar.offlineId, APIKey.calendar_id: calendar.calendar_id.toArray(ofType: Int.self)] as [String: Any]
                    removedCalendars.append(calendar_json)
                })
            }
            offlineRemovedCalendars.append(contentsOf: list)
            eventData[APIKey.calendar_removelist] = removedCalendars

          } //.. end bac que
        }
        })//... main que

TRY 2. use realm in background But i dont know how to use this method

嘗試2.在后台使用領域但我不知道如何使用這種方法

extension Realm {



    func writeAsync<T : ThreadConfined>(obj: T, errorHandler: @escaping ((_ error : Swift.Error) -> Void) = { _ in return }, block: @escaping ((Realm, T?) -> Void)) {
        let wrappedObj = ThreadSafeReference(to: obj)
        let config = self.configuration
        DispatchQueue(label: "background").async {
            autoreleasepool {
                do {
                    let realm = try Realm(configuration: config)
                    let obj = realm.resolve(wrappedObj)

                    try realm.write {
                        block(realm, obj)
                    }
                }
                catch {
                    errorHandler(error)
                }
            }
        }
    }
}

TRY 3. Found one solution but it's not working. it's not executed in a good way. IT's ADD Method, not a get

嘗試3.找到一個解決方案,但它不起作用。它沒有以良好的方式執行。 IT的ADD方法,而不是get

var usersRef: ThreadSafeReference<Results<User>>?
DispatchQueue.global().async {
    autoreleasepool{
        let realm = try! Realm()
        try! realm.write {
            realm.add(users)
        }
        usersRef = ThreadSafeReference(to: users)
    }
}

1 个解决方案

#1


0  

TRY 1 does't work because you can't pass a Realm object reference between threads. What you have to do:

TRY 1不起作用,因為您無法在線程之間傳遞Realm對象引用。你要做什么:

var realmConig: Realm.Configuration = // your config - store it globally

// Now fetch the data
DispatchQueue(label: "background").async {
    // Define a new Realm object inside async thread
    let realm = try! Realm(configuration: realmConfig)
    // now fetch your objects
    let objects = realm.objects(Object.self)
    // From here you can perform actions with the objects
    // i.e. transform if to json format and submit via API
}

Be warned: In order to use objects outside of the background thread, you must transform them into array of ThreadSafeReference first. But it's not needed for your particular case, as far as I understood your goals.

警告:為了使用后台線程之外的對象,必須首先將它們轉換為ThreadSafeReference數組。但就我的理解你的目標而言,並不需要你的具體案例。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2018/05/04/72f416ce4364d4a99aa80af4b544253.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com