2017-09-10 1 views
0

にバックグラウンドスレッドを使用している配列を挿入します。 残りの応答を受け取るとすぐにコールバック関数を呼び出し、配列をバックグラウンドスレッドのdbに挿入します。 私は私があるため、オブジェクトの更にによるキャッチされないにアプリを終了迅速分野私はオブジェクトの配列が、私は<strong>背景</strong>スレッドでレルムDBに挿入し、<strong>メイン</strong>スレッドで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"] 
    } 
} 

...

UIでのレンダリング
DispatchQueue.global().async { 
    let realm = try! Realm() 
    try! realm.write { 
    realm.add(users) 
    } 
} 

...

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 
} 

別の解決策は、メインスレッドにバックグラウンドスレッドからusers配列を渡すThreadSafeReferenceオブジェクトを使用することです。ただし、usersのタイプがResults,Listの場合は、usersのコレクションに1つのThreadSafeReferenceを作成することはできません。タイプResults<User>の場合、usersと仮定して、以下のコードを参照してください。

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 
} 
関連する問題

 関連する問題