简体   繁体   中英

How to insert an object at a specific index in a Realm array?

I have structured my 2D array data model after the example provided by the GroupedTableView example by Realm. However, I am trying to implement the feature to reorder tasks in my tasksByPriority array and am not sure about how to go about inserting at a specific array. At the moment, the Realm Results array is being sorted by dateCreated and I know only how to add new tasks to Realm at the end of the Realm object, not at a specific index.

import UIKit
import MGSwipeTableCell
import RealmSwift
import Realm
import AEAccordion

class TasksTableViewController: UITableViewController {

    var realm: Realm!
    var notificationToken: NotificationToken?
    var priorityIndexes = [0, 1, 2, 3]
    var priorityTitles = ["Urgent | Important", "Urgent | Not Important", "Not Urgent | Important", "Not Urgent | Not       Important"]
    var tasksByPriority = [Results<Task>]()

    override func viewDidLoad() {
        super.viewDidLoad()

        realm = try! Realm()

        notificationToken = realm.addNotificationBlock { [unowned self] note, realm in
            self.tableView.reloadData()
        }

        for priority in priorityIndexes {
            let unsortedObjects = realm.objects(Task.self).filter("priorityIndex == \(priority)")
            let sortedObjects = unsortedObjects.sorted("dateCreated", ascending: true)
            tasksByPriority.append(sortedObjects)
        }
    }


    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return priorityIndexes.count
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return Int(tasksByPriority[section].count)
    }


    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return priorityTitles[section]
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("taskTableViewCell", forIndexPath: indexPath) as! TaskTableViewCell

        // Configure the cell...
        let task = self.taskForIndexPath(indexPath)

            //configure right buttons
        cell.rightButtons = [MGSwipeButton(title: "", icon: UIImage(named:"deleteTask.png"), backgroundColor: UIColor(red: 0, green: 0, blue: 0, alpha: 0), callback: {
                (sender: MGSwipeTableCell!) -> Bool in
                RealmHelper.deleteTask(self.taskForIndexPath(indexPath)!)
                return true
        })]

         return cell
    }

    func taskForIndexPath(indexPath: NSIndexPath) -> Task? {
        return tasksByPriority[indexPath.section][indexPath.row]
    }


    // MARK: Segues

    @IBAction func unwindToTasksTableViewController(sender: UIStoryboardSegue) {
        if let sourceViewController = sender.sourceViewController as? DisplayTaskViewController, task = sourceViewController.task, priorityIndex = sourceViewController.priorityIndex {
            if let selectedIndexPath = tableView.indexPathForSelectedRow {
                // Update an existing task.
                if selectedIndexPath.section == priorityIndex { // not changing priority
                    RealmHelper.updateTask(taskForIndexPath(selectedIndexPath)!, newTask: task)
                }

                else { // changing priority
                    RealmHelper.addTask(task)
                    RealmHelper.deleteTask(taskForIndexPath(selectedIndexPath)!)
                }
            }
            else {
                RealmHelper.addTask(task)
            }
        }

    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if let identifier = segue.identifier {

            if identifier == "editTaskDetailsSegue" {
                let displayTaskViewController = segue.destinationViewController as! DisplayTaskViewController

                // set task of DisplayTaskViewController to task tapped on
                if let selectedTaskCell = sender as? TaskTableViewCell {
                    let indexPath = tableView.indexPathForCell(selectedTaskCell)!
                    let selectedTask = taskForIndexPath(indexPath)
                    displayTaskViewController.task = selectedTask
                    print("Task completed: \(selectedTask!.completed)")
                    displayTaskViewController.priorityIndex = indexPath.section
                    displayTaskViewController.completed = (selectedTask?.completed)!
                }
            }

            else if identifier == "addNewTaskSegue" {
            }
        }
    }
}

Realm Helper Class

import Foundation
import RealmSwift

class RealmHelper {

static func addTask(task: Task) {
    let realm = try! Realm()
    try! realm.write() {
        realm.add(task)
    }
}



static func deleteTask(task: Task) {
    let realm = try! Realm()
    try! realm.write() {
        realm.delete(task)
    }
}

static func updateTask(taskToBeUpdated: Task, newTask: Task) {
    let realm = try! Realm()
    try! realm.write() {
        taskToBeUpdated.text = newTask.text
        taskToBeUpdated.details = newTask.details
        taskToBeUpdated.dueDate = newTask.dueDate
        taskToBeUpdated.completed = newTask.completed
    }
}
}

TL;DR

Objects in Realm are unordered. If you do want to sort the objects you can use List<T> type. A List can be mutated, you can insert(_:atIndex:) , removeAtIndex(_:) and so on. Here is the List Class Reference , where you can find out how use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM