如何编辑领域对象并保存编辑?

时间:2019-05-15 08:34:34

标签: ios swift uitableview realm

我有2个控制器:TableViewController和ViewController。 TableViewController负责显示所有数据,View Controller负责创建新数据。 现在,我想也可以在ViewController中编辑当前数据。单击数据时,我们需要切换到ViewController并将所有默认值替换为当前值。更改并单击保存后,我们返回到TableViewController,在那里我们已经看到了更改。

class OperationsViewController: UITableViewController {

// MARK: - Stored Properties
var transactions: Results<Transaction>!
var sections = [(date: Date, items: Results<Transaction>)]()

// MARK: - UITableViewController Methods
override func viewDidLoad() {
    super.viewDidLoad()
    transactions = realm.objects(Transaction.self)
}

override func viewWillAppear(_ animated: Bool) {
    super .viewWillAppear(animated)
    assembleGroupedTransactions()
    tableView.reloadData()
  }
}

// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let indexPath = tableView.indexPathForSelectedRow {
        let section = sections[indexPath.section]
        let item = section.items[indexPath.row]
        print(item)
        if segue.identifier == "editOrDeleteOperationCell" {
            let addTableViewController = segue.destination as! AddTableViewController
            addTableViewController.defaultTransaction = item
        }
    }
  }
}

// MARK: - User Interface
extension OperationsViewController {

@discardableResult private func assembleGroupedTransactions() -> Array<Any> {
    // fetch all Items sorted by date
    let results = realm.objects(Transaction.self).sorted(byKeyPath: "date", ascending: false)

    sections = results
        .map { item in
            // get start of a day
            return Calendar.current.startOfDay(for: item.date)
        }
        .reduce([]) { dates, date in
            // unique sorted array of dates
            return dates.last == date ? dates : dates + [date]
        }
        .compactMap { startDate -> (date: Date, items: Results<Transaction>) in
            // create the end of current day
            let endDate = Calendar.current.date(byAdding: .day, value: 1, to: startDate)!
            // filter sorted results by a predicate matching current day
            let items = results.filter("(date >= %@) AND (date < %@)", startDate, endDate)
            // return a section only if current day is non-empty
            return (date: startDate, items: items)
    }
    return sections
}

但是当我尝试将当前数据发送到下一个ViewController时,出现错误:

  

***由于未捕获的异常“ RLMException”而终止应用程序,原因:“试图在写事务之外修改对象-首先在RLMRealm实例上调用beginWriteTransaction。”

     

我猜我对Category有问题。看我的模型:

class Transaction: Object {

@objc dynamic var controlStatus = 0

@objc dynamic private var privateCategory: String = Category.consumption.rawValue
var category: Category {
    get { return Category(rawValue: privateCategory)! }
    set { privateCategory = newValue.rawValue }
}

@objc dynamic var amount = "0"
@objc dynamic var date = Date()
@objc dynamic var note = ""
}

controlStatus需求用于监视将来需要的交易状态。其中0是费用,1是收入。 我想的最大问题是我通过enum创建了类别。 我需要根据controlStatus使用类别更改数组。 现在这是我的类别模型:

indirect enum Category: String {
case income = "+"
case consumption = "-"

case salary = "salary"
case billingInterest = "billingInterest"
case partTimeJob = "partTimeJob"

etc.
}

extension Category: RawRepresentable {
typealias RawValue = String

init?(rawValue: RawValue) {
    switch rawValue {
    case "+": self = .income
    case "-": self = .consumption

    case "salary": self = .salary
    case "billingInterest": self = .billingInterest
    case "partTimeJob: self = .partTimeJob
    case "pleasantFinds": self = .pleasantFinds
    case "debtRepayment": self = .debtRepayment

    case "noCategories": self = .noCategories
    case "food": self = .food

    etc. 

    default:
        return nil
    }
}

var rawValue: RawValue {
    switch self {
    case .salary:
        return "salary"
    case .billingInterest:
        return "billingInterest"
    case .partTimeJob:
        return "partTimeJob"
    case .pleasantFinds:
        return "pleasantFinds"
    case .debtRepayment:
        return "debtRepayment"

    case .noCategories:
        return "noCategories"
    case .food:
        return "food"
    case .cafesAndRestaurants:
        return "cafesAndRestaurants"
    etc.
    }
}
}

2 个答案:

答案 0 :(得分:1)

您需要将领域写入事务包含在write块中

try realm.write({ () -> Void in realm.add(object, update: true) })

答案 1 :(得分:0)

来自领域doc

try! realm.write {
    realm.add(myDog)
}