当我尝试编译我的领域代码时遇到了一些错误,这是代码的第一个版本:
import RealmSwift
class Test: Object {
dynamic var name = ""
dynamic var dict = Dictionary<String, Int>()
dynamic var owner: TestList?
}
class TestList: Object{
dynamic var name = ""
let tests = List<Test>().filter("ALL Test.dict[hello] != nil")
}
//ViewController
import RealmSwift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let realm = Realm()
let test1 = Test()
test1.name = "test1"
test1.dict = ["hello": 1]
realm.write{realm.add(test1)}
let test2 = Test()
test2.name = "test2"
test2.dict = ["nihao": 2]
realm.write{realm.add(test2)}
let test3 = Test()
test3.name = "test3"
test3.dict = ["hello": 3]
realm.write{realm.add(test3)}
}
@IBOutlet weak var label: UILabel!
@IBAction func set(sender: UIButton){
let test = Test()
let realm = Realm()
test.name = "not using CoreData"
realm.write{realm.add(test)}
text = "abc"
}
@IBAction func show(sender: UIButton){
let test = Realm().objects(TestList)
var str = ""
println("got to here")
for i in test{
str += " \(i.name)"
}
label.text = str
}
}
通过此设置,我在日志中收到错误消息:
Terminating app due to uncaught exception 'RLMException', reason: 'This method can only be called on RLMArray instances retrieved from an RLMRealm'
当我删除TestList对象中的过滤时,错误变为:Terminating app due to uncaught exception 'RLMException', reason: 'Migration is required for object type 'Test' due to the following errors:
- Property 'dict' has been added to latest object model.
- Property 'owner' has been added to latest object model.'
我是否完全理解Realm的文档?
答案 0 :(得分:1)
第一个错误是对的。您无法对属性进行过滤。此外,Realm目前还不允许字典属性。您需要将其显式建模为专用Realm对象实体的列表属性,该实体具有保存String
和Int
的字段。
class Test: Object {
dynamic var name = ""
dynamic var dict = List<TestRelatedThing>()
dynamic var owner: TestList?
}
class TestRelatedThing : Object {
dynamic var key: String
dynamic var value: Int
}
class TestList: Object{
dynamic var name = ""
let tests = List<Test>()
}
然后,您可以在运行时通过以下方式进行查询:
Realm().objects(TestList).filter("ANY tests.key == %@", "hello")
提示:Realm不支持聚合运算符ALL
。有关支持的运算符的完整列表,请参阅我们的predicate cheat sheet。在这里,由于数据结构的变化,使得TestRelatedThing
与value
属性相等nil
,因此存在量化该操作更有意义。 1}}首先存在。因此,您可以确保存在一个带有键"hello"
的条目。
对于第二个错误:我猜您之前尝试运行代码,并在首次运行模型对象的其他字段之后添加。
您可以重置模拟器状态,也可以只添加以下代码行之一,以确保在开发时每次运行时都使用新的Realm。
# Swift 1.2
var error: NSError?
NSFileManager.defaultManager().removeItemAtPath(Realm.defaultPath, error:&error)
# Swift 2
try! NSFileManager.defaultManager().removeItemAtPath(Realm.defaultPath)