// Get our Realm file's parent directory let folderPath = realm.configuration.fileURL!.deletingLastPathComponent().path
// Disable file protection for this directory try! FileManager.default.setAttributes([FileAttributeKey(rawValue: NSFileProtectionKey): NSFileProtectionNone], ofItemAtPath: folderPath)
可以为每个登录的用户设置独立的数据库
1 2 3 4 5 6 7 8 9
funcsetDefaultRealmForUser(username: String) { var config = Realm.Configuration()
// Use the default directory, but replace the filename with the username config.fileURL = config.fileURL!.deletingLastPathComponent().appendingPathComponent("\(username).realm")
// Set this as the configuration used for the default Realm Realm.Configuration.defaultConfiguration = config }
// Optional int property, defaulting to nil // RealmOptional properties should always be declared with `let`, // as assigning to them directly will not work as desired let age = RealmOptional<Int>() }
let realm = try! Realm() try! realm.write() { var person = realm.create(Person.self, value: ["Jane", 27]) // Reading from or modifying a `RealmOptional` is done via the `value` property person.age.value = 28 }
添加主键,可以指定某个属性字段为主键,但必须唯一。
1 2 3 4 5 6 7 8
classPerson: Object{ @objcdynamicvar id = 0 @objcdynamicvar name = ""
// Get the default Realm let realm = try! Realm() // You only need to do this once (per thread)
// Add to the Realm inside a transaction try! realm.write { realm.add(myDog) }
// Update an object with a transaction try! realm.write { author.name = "Thomas Pynchon" }
// Create or Insert an record try! realm.write { realm.create(Book.self, value: ["id": 1, "price": 9000.0], update: true) }
// Delete an object with a transaction try! realm.write { realm.delete(cheeseBook) }
Queries
通过 Realm, 我们可以很方便的查询数据库
1 2
// retrieves all Dogs from the default Realm let dogs = realm.objects(Dog.self)
通过指定查询条件查询
1 2 3 4 5 6
// 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)
还可以通过指定 keyPath 对查询结果排序
1 2 3 4 5 6 7 8 9 10 11
lass Person: Object { @objcdynamicvar name = "" @objcdynamicvar dog: Dog? } classDog: Object{ @objcdynamicvar name = "" @objcdynamicvar age = 0 }
let dogOwners = realm.objects(Person.self) let ownersByDogAge = dogOwners.sorted(byKeyPath: "dog.age")
// Inside your application(application:didFinishLaunchingWithOptions:)
let config = Realm.Configuration( // Set the new schema version. This must be greater than the previously used // version (if you've never set a schema version before, the version is 0). schemaVersion: 1,
// Set the block which will be called automatically when opening a Realm with // a schema version lower than the one set above migrationBlock: { migration, oldSchemaVersion in // We haven’t migrated anything yet, so oldSchemaVersion == 0 if (oldSchemaVersion < 1) { // The enumerateObjects(ofType:_:) method iterates // over every Person object stored in the Realm file migration.enumerateObjects(ofType: Person.className()) { oldObject, newObject in // combine name fields into a single field let firstName = oldObject!["firstName"] as! String let lastName = oldObject!["lastName"] as! String newObject!["fullName"] = "\(firstName)\(lastName)" } } })
// Tell Realm to use this new configuration object for the default Realm Realm.Configuration.defaultConfiguration = config
// Now that we've told Realm how to handle the schema change, opening the file // will automatically perform the migration let realm = try! Realm()