我每2分钟从数据库中获取数据并在API中发布数据。我的应用程序每2分钟就会停留一段时间。原因是当我从数据库获取时间应用程序卡住的数据时。我必须在后台做。
这是我的代码正在运行,但应用程序是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
}
尝试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)
}
}
答案 0 :(得分:0)
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
数组。但就我的理解你的目标而言,并不需要你的具体案例。