複数のResultsを結合して1つのコレクションにするよりは、複数のResultsを1つのデータソースであるかのように見せかけるとする方が、都合がいいです。
これはTableViewの使い方の問題なので、Realmだけでなく他のコレクションをデータソースに使用している場合でも同様に使えます。
例えば、下記のように3つの別々の条件でフィルタしたResultsがあるとします。
swift
1results1 = realm.objects(SomeClass.self).filter("...")
2results2 = realm.objects(SomeClass.self).filter("...")
3results3 = realm.objects(SomeClass.self).filter("...")
これを1つのテーブルで表示するには、まずテーブルの件数に3つのResultsを合計した値を返します。
swift
1func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
2 return results1.count + results2.count + results3.count
3}
そうすると、3つのResultsの件数ぶん、データがテーブルビューから要求されるので、results1
の件数を超えたぶんはresults2
へ、results2
の件数を超えたぶんはresults3
の要素から値を取り出して返します。
swift
1func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
2 let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell
3 if indexPath.row < results1.count {
4 let data = results1[indexPath.row]
5 ...
6 } else if indexPath.row < results1.count + results2.count {
7 let data = results1[indexPath.row - results1.count]
8 ...
9 } else {
10 let data = results1[indexPath.row - results1.count - results2.count]
11 ...
12 }
13
14 return cell
15}
このようにすると、複数のコレクションを1つのコレクションであるかのように連続してテーブルビューで扱うことができます。Realm以外のデータソースでも利用できるテクニックです。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2016/06/30 04:46