Created
April 5, 2017 09:05
-
-
Save syou007/801fa5ddbd11d1d57ac0255938f65b41 to your computer and use it in GitHub Desktop.
RealmのIDを自動採番(オートインクリメント)する方法 ref: http://qiita.com/syou007/items/267612c402fdd28de7a8
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 RObject: Object { | |
// ID | |
dynamic var id = 0 | |
// データを保存。 | |
func save() { | |
let realm = try! Realm() | |
if realm.isInWriteTransaction { | |
if self.id == 0 { self.id = self.createNewId() } | |
realm.add(self, update: true) | |
} else { | |
try! realm.write { | |
if self.id == 0 { self.id = self.createNewId() } | |
realm.add(self, update: true) | |
} | |
} | |
} | |
// 新しいIDを採番します。 | |
private func createNewId() -> Int { | |
let realm = try! Realm() | |
return (realm.objects(type(of: self).self).sorted(byKeyPath: "id", ascending: false).first?.id ?? 0) + 1 | |
} | |
// プライマリーキーの設定 | |
override static func primaryKey() -> String? { | |
return "id" | |
} | |
} |
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 User: RObject { | |
// 名前 | |
dynamic var name = "" | |
} |
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
let user = User() | |
user.name = "hoge" | |
user.save() |
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
let realm = try! Realm() | |
let user = realm.objects(User.self).first ?? User() | |
try! realm.write { | |
user.name = "hoge" | |
user.save() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment