如何使用Realm存储字符串枚举

时间:2019-05-07 16:05:06

标签: ios swift realm

我无法在Realm中将数据另存为枚举。当我跟踪变量的状态并保存时,旧值仍然保留,而不是新值。我在做什么错了?

我使用了一个setter和一个getter,但是问题仍然没有解决。

import RealmSwift

class Transaction: Object {

var accounting: Accounting = .income
@objc dynamic var amount = 0
@objc dynamic var date = ""
@objc dynamic var note = ""

private var privateCategory: String = Category.noCategories.rawValue
var category: Category {
    get { return Category(rawValue: privateCategory)! }
    set { privateCategory = newValue.rawValue }
  } 
}

enum Category: String {
   case noCategories = "No сategories"
   case food = "Food"
   case cafesAndRestaurants = "Cafes And Restaurants"
   case manufacturedGoods = "Manufactured Goods"
   case forceMajeure = "Force Majeure"
   case entertainment = "Entertainment"
}

当我尝试保存属性时,默认情况下会保存Сategory(“无类别”)

let transactionOne = Transaction()
    transactionOne.accounting = .consuption
    transactionOne.amount = 250
    transactionOne.category = .food
  

transaction privateCategory字符串“无类别”

1 个答案:

答案 0 :(得分:1)

Realm guide中的所有示例中可以看出,要保留的字符串属性用@objc dynamic标记。因此,您也应该将privateCategory标记为@objc dynamic

@objc dynamic var privateCategory: String = Category.noCategories.rawValue