目前我有Transaction
具有 transactionDate
的对象:
class Transaction: Object {
@objc dynamic var transactionDate: String = "" // yyyy-MM-dd
}
我有很多这样的对象,我只需要删除旧的(超过两年的),所以我写道:
// Since now is 2017-09 I need to delete all objects before 2015-09
// calculations are out of scope here I think :)
realm.objects(Transaction.self).filter("transactionDate < '2015-09-30'")
但是我遇到了一个异常(exception):
Invalid operator type', reason: 'Operator '<' not supported for string type.
我无法使用<
字符串的运算符。我怎样才能搜索
这些旧弦? (这样我就可以删除它们)
最佳答案
您不能使用<
对于一个字符串。可能更好的方法是使用 Collection
的filter
方法。您可以通过闭包传递条件,然后可以将字符串对象转换为 Date
目的。就像下面这样:
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .gregorian)
formatter.dateFormat = "yyyy-MM-dd"
let filtered = realm.objects(Transaction.self)
.filter { formatter.date(from: $0.transactionDate)! < formatter.date(from: "2015-09-30")! }
缺点:它不使用 Realm 的 native 查询,因此 Realm 的延迟加载不起作用。但这不是问题,因为我认为这个过程不会被多次调用。
关于ios - 如何在 Realm 中使用 < 或 <= 运算符搜索对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46363271/