ios – Realm.io – 从不正确的线程swift访问的域

前端之家收集整理的这篇文章主要介绍了ios – Realm.io – 从不正确的线程swift访问的域前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想从我的.json文件下载城市(name,id,lon,lat)到Realm数据库.

我创建了名为City的Realm对象,但它崩溃时出现以下错误

Terminating app due to uncaught exception 'RLMException',reason: 'Realm accessed from incorrect thread'**

所以,我只想在我的self.cities([City])数组中获得一个Realm对象.然后把它放在表格视图中.

我的刷新功能

func refresh(sender:AnyObject)
{

        var service = CityService()

        service.getCities {
            (response) in

            if(response.count > 0){
                if(response["cities"] != nil){
                    self.citiesStore.loadCities(response["cities"]! as NSArray,tableView: self.tableView)
                    self.tableView.reloadData()
                } else {
                    println("No response data")
                }
            }

}

服务:

class CityService {
var getCityUrl = "http://test:8888/cities.json";

func getCities(callback:(NSDictionary)->()) {
    get(getCityUrl,callback:callback)
}

func get(url:String,callback:(NSDictionary) -> ()){
    var nsURL = NSURL(string: url)

    UIApplication.sharedApplication().networkActivityIndicatorVisible = true

    let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL!) {
        (data,response,error) in
        var error: NSError?

        UIApplication.sharedApplication().networkActivityIndicatorVisible = false

        if(error == nil){
            if(response != nil){
                var response = NSJSONSerialization.JSONObjectWithData(data,options: NSJSONReadingOptions.MutableContainers,error: &error) as NSDictionary
                callback(response)
            } else {
                callback(NSDictionary())
            }
        }

    }

    task.resume()
}

}

和loadCities功能

func loadCities(citiesJson:NSArray,tableView: UITableView) {

    var realmQueue = dispatch_queue_create("db",DISPATCH_QUEUE_SERIAL)

    let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
    dispatch_async(realmQueue) {
        println("start")

        var cc:[City] = []


        var realm = RLMRealm.defaultRealm()

        realm.beginWriteTransaction()

        for object in citiesJson {

            City.createOrUpdateInRealm(realm,withObject: object)

        }

        realm.commitWriteTransaction()

        let citiesFromRealm = City.allObjects()

        for object in citiesFromRealm {
            let cityObject = object as City

            //println(cityObject.name)  <-- here ok

            cc.append(cityObject)
        }

        println("point")

        dispatch_async(dispatch_get_main_queue()) {
            println("ok")
            self.cities.removeAll(keepCapacity: false)
            self.cities = cc

            println(self.cities[3].name) // <--- Here an error

            tableView.reloadData()
        }
    }


}

解决方法

例外是告诉你到底发生了什么 – 一个RLMRealm实例(以及从它获得的所有对象)仅在单个线程上有效.每次调度到一个单独的队列时,您都需要创建一个新的RLMRealm实例,并在访问任何属性或启动新的写入事务之前重新获取RLMObjects.
原文链接:https://www.f2er.com/iOS/330094.html

猜你在找的iOS相关文章