Created
October 17, 2016 10:26
-
-
Save llibra/a80987bb5bb261f8d2d94696fa41777c to your computer and use it in GitHub Desktop.
自分用Realmサンプルコード
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Dog: Object { | |
dynamic var name = "" | |
dynamic var age = 0 | |
} | |
func testExample() { | |
let dog = Dog() | |
dog.name = "Rex" | |
dog.age = 1 | |
let realm = try! Realm() | |
let puppies = realm.objects(Dog.self).filter("age < 2") | |
XCTAssertEqual(puppies.count, 0) | |
try! realm.write { | |
realm.add(dog) | |
} | |
// クエリの結果は自動更新される | |
XCTAssertEqual(puppies.count, 1) | |
DispatchQueue(label: "background").async { | |
// スレッド間でRealmオブジェクトの共有はできないので新規に作成する必要がある | |
let realm = try! Realm() | |
let dogs = realm.objects(Dog.self).filter("age == 1") | |
// クエリの結果は更新を自動的に反映してしまうため | |
// for dog in dogs { dog.age = 3 }などと更新すべきではない | |
try! realm.write { | |
dogs.setValue(3, forKeyPath: "age") | |
} | |
} | |
// 別スレッドが終了するまで待機 | |
sleep(3) | |
// XCTestの実行スレッドは実行ループを持たないので明示的なリフレッシュが必要 | |
realm.refresh() | |
// クエリの結果も更新されるので条件に一致するオブジェクトは0件になる | |
XCTAssertEqual(puppies.count, 0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment