我想从我的.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() } } }