我使用TableView,表格的单元格中有一个按钮,当用户单击该按钮时,我需要从表格中删除该项目。
并且我尝试使用filter
进行删除,但这是行不通的。
在我的表格视图单元格中:
import UIKit
import GMStepper
import RealmSwift
class CartTableViewCell: UITableViewCell {
@IBOutlet weak var foodTitle: UILabel!
@IBOutlet weak var foodPrice: UILabel!
@IBOutlet weak var shortDiscription: UILabel!
@IBOutlet weak var myStepper: GMStepper!
@IBOutlet weak var deleteButton: UIButton!
var food : Foods?
weak var delegate: CartTableViewCellDelegate?
let realm = try! Realm()
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
@IBAction func myFuncStepper(_ sender: GMStepper) {
if sender.value == food?.count {
return
}
try! realm.write {
food?.count = sender.value
food?.name = foodTitle.text!
food?.price = Double(foodPrice.text!)!
}
}
//here , when the user has clicked at the button i need remove this
item from table
@IBAction func deletButtonFunc(_ sender: Any) {
if let userObject = realm.objects(Foods.self).filter("id == 0").first {
print("User is existed, it's being deleted.")
try! realm.write {
realm.delete(userObject)
}
print("Deleted.")
}
else{
print("User is not found.")
}
}
}
我的ViewController:
import UIKit
import RealmSwift
class CartViewController: UIViewController , UITableViewDataSource{
var foood : Foods?
var foodArrayCart = [Foods]()
weak var cells : FoodsSecoundTableViewCellDelegate?
var countMeal:Int?
let realm = try! Realm()
@IBOutlet weak var myTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let result = realm.objects(Foods.self)
for obje in result {
foodArrayCart.append(obje)
}
myTable.rowHeight = 182
myTable.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return foodArrayCart.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let arr = foodArrayCart[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "cart_cell") as! CartTableViewCell
if cell.foodPrice.text! == "nil" {
cell.foodPrice.text = String(arr.price)
}
cell.shortDiscription.text = arr.name
cell.foodTitle.text = arr.name
cell.foodPrice.text = String(arr.price)
cell.myStepper.value = arr.count
cell.food?.id = arr.id
cell.myStepper.tag = indexPath.row
return cell
}
}
课程:
import Foundation
import UIKit
import RealmSwift
import Realm
class Foods : Object {
@objc dynamic var id = 0
@objc dynamic var name = ""
@objc dynamic var price = 0.0
@objc dynamic var descriptionn = ""
@objc dynamic var time = ""
@objc dynamic var rating = 0.0
var image:UIImage?
@objc dynamic var count = 0.0
override static func primaryKey() -> String?{
return "id"
}
convenience init(id : Int , name : String,price : Double , count:Double ,description : String,time : String,rating : Double,image : UIImage?) {
self.init()
self.id = id
self.name = name
self.price = price
self.descriptionn = description
self.time = time
self.rating = rating
self.image = image
self.count = count
}
convenience init(id : Int , name : String,price : Double , count : Double) {
self.init()
self.id = id
self.name = name
self.price = price
self.count = count
}
}
答案 0 :(得分:0)
问题在于您没有订阅有关结果的通知,因此当结果更改时,您什么也没做(即更新tableView)。您会发现Realm文档中有一个观察示例,该示例显示了如何根据集合更改here更新表视图。
TLDR,而领域结果是自动更新的,如果您需要将某些内容同步到那些结果(例如,表视图中的单元格),则需要观察结果并将同步代码写入observe块中。
lass ViewController: UITableViewController {
var notificationToken: NotificationToken? = nil
override func viewDidLoad() {
super.viewDidLoad()
let realm = try! Realm()
let results = realm.objects(Person.self).filter("age > 5")
// Observe Results Notifications
notificationToken = results.observe { [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()
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()
case .error(let error):
// An error occurred while opening the Realm file on the background worker thread
fatalError("\(error)")
}
}
}
deinit {
notificationToken?.invalidate()
}
}