let dogs = realm.objects(Dog.self) // retrieves all Dogs from the default Realm
// Query using a predicate string var tanDogs = realm.objects(Dog.self).filter("color = 'tan' AND name BEGINSWITH 'B'")
// Query using an NSPredicate let predicate = NSPredicate(format: "color = %@ AND name BEGINSWITH %@", "tan", "B") tanDogs = realm.objects(Dog.self).filter(predicate)
// Sorting let sortedDogs = realm.objects(Dog.self).filter("color = 'tan' AND name BEGINSWITH 'B'").sorted(byKeyPath: "name")
Realm 中的所有查询都是懒加载,当你执行上面这些代码的时候,真正的数据并不会加载到内存中,只有当 Model 的属性被真正访问的时候,它才回被加载。而且查询出来的结果是实时更新的。当数据发生变化时不需要再重新查询一遍。
classViewController: UITableViewController{ var notificationToken: NotificationToken? = nil
overridefuncviewDidLoad() { super.viewDidLoad() let realm = try! Realm() let results = realm.objects(Person.self).filter("age > 5")
// Observe Results Notifications notificationToken = results.observe { [weakself] (changes: RealmCollectionChange) in guardlet tableView = self?.tableView else { return } switch changes { case .initial: // Results are now populated and can be accessed without blocking the UI tableView.reloadData() case .update(_, let deletions, let insertions, let modifications): // Query results have changed, so apply them to the UITableView tableView.beginUpdates() tableView.insertRows(at: insertions.map({ IndexPath(row: $0, section: 0) }), with: .automatic) tableView.deleteRows(at: deletions.map({ IndexPath(row: $0, section: 0)}), with: .automatic) tableView.reloadRows(at: modifications.map({ IndexPath(row: $0, section: 0) }), with: .automatic) tableView.endUpdates() case .error(let error): // An error occurred while opening the Realm file on the background worker thread fatalError("\(error)") } } }
let dic = ["name": "lijun", "age": 30] as [String : Any] let data = try! JSONSerialization.data(withJSONObject: dic, options: []) let person = try? JSONDecoder().decode(Person.self, from: data)
structPerson: Codable{ let name: String let age: Int?
enumCodingKeys: String, CodingKey{ case name = "title" case age } }
let dic = ["title": "lijun", "age": 30] as [String : Any] let data = try! JSONSerialization.data(withJSONObject: dic, options: []) let person = try? JSONDecoder().decode(Person.self, from: data)