我想从我的.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()
}
}
}
答案 0 :(得分:12)
该异常正在告诉您究竟发生了什么 - RLMRealm
个实例(以及从中获取的所有对象)仅在单个线程上有效。每次分派到单独的队列时,您都需要创建一个新的RLMRealm
实例,并在访问任何属性或开始新的写入事务之前重新获取RLMObject
。