基于领域注释的应用未正确删除正确对象

时间:2018-07-08 09:43:26

标签: xcode uitableview realm reloaddata

删除单元格时,列表末尾的项目将代替刚删除的项目。仅当列表中有3个以上的项目时,才会发生这种情况。

在下面的gif文件中,我删除了数字3和4,这在模拟器中留下了数字1,2,5。 但是在领域文件中,我有数字1,2,4。我不知道为什么会这样吗?

数据模型

import Foundation
import RealmSwift

class Item: Object {
    @objc dynamic var name = ""

}

视图控制器

import UIKit
import RealmSwift

class ListViewController: UITableViewController {

let realm = try! Realm()
var itemArray : Results<Item>?

var item:Item?

override func viewDidLoad() {
    super.viewDidLoad()

    self.itemArray = realm.objects(Item.self)

}

@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {

    var textField = UITextField()
    let alert = UIAlertController(title: "Add New Item", message: "", preferredStyle: .alert)
    alert.view.tintColor = UIColor.red

    let action = UIAlertAction(title: "Add Item", style: .default) { (action) in

     let newItem = Item()
     newItem.name = textField.text!

        try! self.realm.write {

            self.realm.add(newItem)

        }
        self.tableView.reloadData()

    }
    alert.addTextField { (alertTextField) in
        alertTextField.placeholder = "Create new item"
        textField = alertTextField

    }
    alert.addAction(action)
    present(alert, animated: true, completion: nil)

}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.itemArray!.count//Size of the Array
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath)//Asigns the Protocol Cell
    let data = self.itemArray![indexPath.row]
    cell.textLabel?.text = data.name

    return cell
}

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete { 
        if let item = itemArray?[indexPath.row] {

            try! self.realm.write {
                self.realm.delete(item)
            }
            tableView.deleteRows(at: [indexPath], with: .automatic)
        }

    }
}

1 个答案:

答案 0 :(得分:1)

您正在从Realm检索一个未排序的结果集,根据文档,该结果集不一定会在删除后保留插入顺序(基本上是在删除public class Test extends MainActivity implements MainActivity.MyInterfcae { Context context; @Override public void test0(final Context context) { this.context = context; Button b = (Button) ((Activity)context).findViewById(R.id.button0); b.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { Toast toast = Toast.makeText(context, "Implemented!", Toast.LENGTH_SHORT); toast.show(); } }); } } 之后,3移到其位置):< / p>

  

请注意,只有对查询排序后,结果的顺序才能保证保持一致。出于性能原因,不能保证保留插入顺序。

所以您可以做两件事:

1。)对结果集进行排序

2。)而不是假设您只删除单个对象并且没有任何形式的移动,而是可以依靠Realm自己的带有通知令牌的diffing + change set评估,以便为任何对象获得更改集结果集可能发生的变化。

5