它似乎!我已经尝试了一切,但我做不到。

我每2分钟从数据库中获取数据并在API中发布数据。每2分钟我的应用程序停留几秒钟。原因是当我从数据库中获取数据时,应用程序卡住了。我必须在后台做。

这是我的代码正在运行,但应用程序卡住了

 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
            }


尝试1。尝试在后台运行代码,我必须尝试使用​​调度队列

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


尝试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)
                }
            }
        }
    }
}


尝试3。找到一个解决方案,但不起作用。它执行得不好。 IT的ADD方法

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

最佳答案

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
}


警告:为了在后台线程之外使用objects,必须首先将它们转换为ThreadSafeReference数组。但是据我了解您的目标,对于您的特定情况并不需要。

关于swift - 在后台线程中快速运行Realm,然后应用崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50173019/

10-12 01:25