2017-09-10 29 views
0

我有经由其余响应,这是我要插入到境界分贝在背景线程并在uicollectionview在线程中使用接收到的对象的数组。 只要我收到来自休息的响应,我会调用回调函数并在后台线程中将数组插入数据库。插入背景 当我试图在对象的主线程属性访问的问题,我得到异常(见下文),我认为是因为还未插入迅速境界插入件阵列中的后台线程使用在主

终止应用程序由于未捕获的对象异常'RLMException',原因: '从不正确的线程访问的领域。

模型

class User : Object, Mappable { 
    dynamic var firstName: String? 
    dynamic var lastName: String? 

    required convenience init?(map: Map){ 
     self.init() 
    } 

    func mapping(map: Map) { 
     firstName <- map["firstName"] 
     lastName <- map["lastName"] 
    } 
} 

在后台线程插入...

DispatchQueue.global().async { 
    let realm = try! Realm() 
    try! realm.write { 
    realm.add(users) 
    } 
} 

渲染UI ...

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! UserViewCell 

    let user = users[indexPath.row] 
    cell.firstName.text = user.firstName 
    cell.lastName.text = user.lastName 
} 

请注意,发生异常或者在访问firstName或lastName。

请让我知道我在做什么错在这里

+1

您是否考虑过使用notificationToken? – EpicPandaForce

+0

这是我唯一想到的,但不知道这是不是主意 – mihatel

+0

这是Realm的通知令牌 – EpicPandaForce

回答

1

最简单的解决方案是创建一个新的引用您的领域实例在主线程,并使用新创建的参考,从境界获取所有用户,所以你将从同一个线程访问领域。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! UserViewCell 

    let users = try! Realm().objects(User.self) 
    let user = users[indexPath.row] 
    cell.firstName.text = user.firstName 
    cell.lastName.text = user.lastName 
} 

另一种解决方案是使用一个ThreadSafeReference对象从背景线程users数组传递给主线程。但是,如果users的类型为ListResults,则只能为users的集合创建单个ThreadSafeReference。假设users如果类型为Results<User>,请参见下面的代码。

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! UserViewCell 

    let realm = try! Realm() 
    guard let usersRef = usersRef, let users = realm.resolve(usersRef) else {return} 
    let user = users[indexPath.row] 
    cell.firstName.text = user.firstName 
    cell.lastName.text = user.lastName 
}