gpt4 book ai didi

iOS Realm 结果<对象> 无法添加结果<项目>

转载 作者:行者123 更新时间:2023-11-29 11:46:17 25 4
gpt4 key购买 nike

我尝试为 Realm 结果创建通用的 UITableView 数据源类,但是当我尝试发送不同于Results<<>Object<>> 示例 Results 我收到此错误消息:

Cannot convert value of type 'Results'<'Project'>' to expected element type 'Results'<'Object'>'

class RealmResultsTableViewDataSource: TableViewDataSource {

var realmResults:[Results<Object>]
var notificationTokens: [NotificationToken] = []

init(tableView: UITableView, realmResults: [Results<Object>], configCell: @escaping TableViewConfigCellBlock, canEdit: TableViewCanEditCellBlock?, canMove: TableViewCanMoveRowBlock?, commitEditing: TableViewCommitEditingStyleBlock?) {

self.realmResults = realmResults

super.init(tableView: tableView, dataSource: [], configCell: configCell, canEdit: canEdit, canMove: canMove, commitEditing: commitEditing)

addTokens(for: realmResults)
}

deinit {
for token in notificationTokens {
token.stop()
}
}

override var sections: Int{
get { return realmResults.count }
}

override func numberOfRows(section: Int) -> Int {
return realmResults[section].count
}

// MARK: Add tokens

func addTokens(for results: [Results<Object>]) {
for result in results {

let notificationToken = result.addNotificationBlock { [weak self] (changes: RealmCollectionChange) in
guard let tableView = self?.tableView else { return }
switch changes {
case .initial:
// Results are now populated and can be accessed without blocking the UI
tableView.reloadData()
break
case .update(_, let deletions, let insertions, let modifications):
// Query results have changed, so apply them to the UITableView
tableView.beginUpdates()
tableView.insertRows(at: insertions.map({ IndexPath(row: $0, section: 0) }),
with: .automatic)
tableView.deleteRows(at: deletions.map({ IndexPath(row: $0, section: 0)}),
with: .automatic)
tableView.reloadRows(at: modifications.map({ IndexPath(row: $0, section: 0) }),
with: .automatic)
tableView.endUpdates()
break
case .error(let error):
// An error occurred while opening the Realm file on the background worker thread
fatalError("\(error)")
break
}
}

notificationTokens.append(notificationToken)
}
}

override func dataSourceObject(on indexPath: IndexPath) -> Any {

return realmResults[indexPath.section][indexPath.row]
}

和:

让境界=尝试!境界()

    let result = realm.objects(Project.self).filter("id < 10").sorted(byKeyPath: "id", ascending: true)

tableViewDataSource = RealmResultsTableViewDataSource(tableView: tableView, realmResults: [result], configCell: { (tableView, indexPath, object) -> UITableViewCell in

let cell = tableView.dequeueReusableCell(withIdentifier:ProjectListTableViewCell.cellIdentifier , for: indexPath)

return cell

}, canEdit: nil, canMove: nil, commitEditing: nil)



import RealmSwift

class Project: Object {

dynamic var id: Int = 0
dynamic var name: String = ""
}

解决方法:

class RealmResultsTableViewDataSource<T: Object>: TableViewDataSource {

var realmResults:Results<T>
var notificationTokens: [NotificationToken] = []


init(tableView: UITableView, realmResults: Results<T>, configCell: @escaping TableViewConfigCellBlock, canEdit: TableViewCanEditCellBlock?, canMove: TableViewCanMoveRowBlock?, commitEditing: TableViewCommitEditingStyleBlock?) {

self.realmResults = realmResults

super.init(tableView: tableView, dataSource: [], configCell: configCell, canEdit: canEdit, canMove: canMove, commitEditing: commitEditing)


addTokens(for: self.realmResults)
}

deinit {

for token in notificationTokens {
token.stop()
}
}

override var sections: Int{

get{
return 1
}
}

override func numberOfRows(section: Int) -> Int {
return realmResults.count
}


// MARK: Add tokens

func addTokens(for results: Results<T>) {

let notificationToken = results.addNotificationBlock { [weak self] (changes: RealmCollectionChange) in
guard let tableView = self?.tableView else { return }
guard tableView.dataSource === self else { return }
switch changes {
case .initial:
// Results are now populated and can be accessed without blocking the UI
tableView.reloadData()
break
case .update(_, let deletions, let insertions, let modifications):
// Query results have changed, so apply them to the UITableView
tableView.beginUpdates()
tableView.insertRows(at: insertions.map({ IndexPath(row: $0, section: 0) }),
with: .automatic)
tableView.deleteRows(at: deletions.map({ IndexPath(row: $0, section: 0)}),
with: .automatic)
tableView.reloadRows(at: modifications.map({ IndexPath(row: $0, section: 0) }),
with: .automatic)
tableView.endUpdates()
break
case .error(let error):
// An error occurred while opening the Realm file on the background worker thread
fatalError("\(error)")
break
}
}

notificationTokens.append(notificationToken)
}

override func dataSourceObject(on indexPath: IndexPath) -> Any {

return realmResults[indexPath.row]
}

override func removeObject(indexPath: IndexPath) {
// assertionFailure("you can use ramoveObject int \(String(describing: self))")
}

}

最佳答案

据我所知,Realm Swift 还不支持多态。

The current solution is to use composition instead of inheritance. There are lots of good argument about it (Gang of Four and Joshua Bloch to mention some prestigious supporters of this approach).

On the other hand we are considering to allow inheritance, but it would not allow queries. For example: Animal which is extended both by Dog, Cat and Duck. You would not be able to query Animals with for legs and have all Dogs and Cats, but not Ducks. We feel this would be a very crippling behavior but are eager to listen to more opinions.

这在此处讨论(讨论产品的 java 版本,因此它只是您的起点...):https://github.com/realm/realm-java/issues/761

最简单的解决方案 [但如果您需要将这些方法与 Object 的其他子类一起重用,则可能不是最好的] 是替换“对象”与“项目”

关于iOS Realm 结果<对象> 无法添加结果<项目>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43695517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com