xcode - 使用 Swift 在 tableView 中重新排序 Realm.io 数据

标签 xcode uitableview swift realm

我已经使用 Realm.io 实现了一个 ios 应用程序的基本示例

我希望能够在我的 iOS 应用程序中对表格行重新排序并将订单保存回 Realm。 为此,Realm 模型包含一个名为 position 的属性。

P.S:对不起,代码太多了。

import UIKit
import Realm

class Cell: UITableViewCell {
    var position: Int!
    init(style: UITableViewCellStyle, reuseIdentifier: String!) {
        super.init(style: .Subtitle, reuseIdentifier: reuseIdentifier)
    }
}

class Language: RLMObject {
    var title = ""
    var position = Int()
}

class ManagerLanguagesController: UITableViewController, UITableViewDelegate, UITableViewDataSource {

    var array = RLMArray()
    var notificationToken: RLMNotificationToken?
    var editButton = UIBarButtonItem()

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        notificationToken = RLMRealm.defaultRealm().addNotificationBlock { note, realm in
            self.reloadData()
        }
        reloadData()
    }

    override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
        return Int(array.count)
    }

    func setupUI() {
        tableView.registerClass(Cell.self, forCellReuseIdentifier: "cell")
        self.title = "Languages"    
        var addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "add")
        editButton = UIBarButtonItem(title: "Edit", style: .Plain, target: self, action: "edit")
        var buttons = [addButton, editButton]
        self.navigationItem.rightBarButtonItems = buttons
    }

    func add() {
        var addLanguageView:UIViewController = self.storyboard.instantiateViewControllerWithIdentifier("newLanguage") as UIViewController
        self.navigationController.presentViewController(addLanguageView, animated: true, completion: nil)
    }

    func edit () {
        if tableView.editing {      
            /* FROM THIS POINT I'M PROBABLY DOING SOMETHING WRONG.. IT IS NOT WORKING  */
            var positionArray = NSMutableArray()
            let realm = RLMRealm.defaultRealm()
            var i = 0

            for var row = 0; row < tableView.numberOfRowsInSection(0); row++ {
                var cellPath = NSIndexPath(forRow: row, inSection: 0)
                var cell:Cell = tableView.cellForRowAtIndexPath(cellPath) as Cell
                positionArray.addObject(cell.position)
            }

            realm.beginWriteTransaction()
            for row: RLMObject in array {
                row["position"] = positionArray[i]
                i++
            }
            realm.commitWriteTransaction()

            /* -- NOT WORKING END -- */

            tableView.setEditing(false, animated: true)
            editButton.style = UIBarButtonItemStyle.Plain
            editButton.title = "Edit"
        } else{
            tableView.setEditing(true, animated: true)
            editButton.title = "Done"
            editButton.style =  UIBarButtonItemStyle.Done
        }
    }

    override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
        let cell = tableView!.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as Cell
        let object = array[UInt(indexPath!.row)] as Language
        cell.textLabel.text = object.title
        cell.position = object.position // I have implemented this to be able to retain initial positions for each row and maybe use this when reordering..
        return cell
    }

    override func tableView(tableView: UITableView!, canMoveRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
        return true
    }

    override func tableView(tableView: UITableView!, moveRowAtIndexPath sourceIndexPath: NSIndexPath!, toIndexPath destinationIndexPath: NSIndexPath!) {
        //  println("Old index: \(sourceIndexPath.indexAtPosition(sourceIndexPath.length - 1)+1)")
        //  println("New index: \(destinationIndexPath.indexAtPosition(sourceIndexPath.length - 1)+1)")
        // Maybe something needs to be implemented here instead...
    }

    func reloadData() {
        array = Language.allObjects().arraySortedByProperty("position", ascending: true)
        tableView.reloadData()
    }

}

提前致谢

最佳答案

您可以不使用位置属性,而是将有序数组作为另一个对象的属性。这样您就不必更新位置,而是根据需要安排您的对象:

class Language: RLMObject {
    dynamic var title = ""
}

class LanguageList: RLMObject {
    dynamic var languages = RLMArray(objectClassName: "Language")
}

class ManagerLanguagesController: UITableViewController, UITableViewDelegate, UITableViewDataSource {

    override func viewDidLoad() {
        super.viewDidLoad()

        // create our list
        var realm = RLMRealm.defaultRealm()
        realm.beginWriteTransaction()
        realm.addObject(LanguageList())
        realm.commitWriteTransaction()
        ...
    }

    // helper to get the RLMArray of languages in our list
    func array() -> RLMArray {
        return (LanguageList.allObjects().firstObject() as LanguageList).languages
    }

    override func tableView(tableView: UITableView!, moveRowAtIndexPath sourceIndexPath: NSIndexPath!, toIndexPath destinationIndexPath: NSIndexPath!) {
        var languages = array()
        var object = languages.objectAtIndex(UInt(sourceIndexPath.row)) as Language
        var realm = RLMRealm.defaultRealm()
        realm.beginWriteTransaction()                
        languages.removeObjectAtIndex(UInt(sourceIndexPath.row))
        languages.insertObject(object, atIndex: UInt(destinationIndexPath.row))
        realm.commitWriteTransaction()
    }

    ...
}

关于xcode - 使用 Swift 在 tableView 中重新排序 Realm.io 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25023826/

相关文章:

iphone - 警告 : check_safe_call: could not restore current frame

objective-c - 检查 NavigationItem.title 是否等于 @"part"

objective-c - 在单元格中设置图标图像的问题

swift - 外围设备未连接 - Swift

ios - 无论 UIViewContentMode 选择如何,部分屏幕视频预览都会失真

ios - 从 UINavigationController 堆栈转出到 UITabBarController

ios - 播放器 SKPhysicsBody 通过其他 SKPhysicsBody swift 4 Xcode 9

ios - 如何等到 UITableView 内置动画完成?

ios - 根据 UITextView 的 contentSize 调整特定表格 View 单元格的大小

ios - 使用代码 "setImage"设置按钮图像时出现问题