-
-
Save ainame/f71a291947c051b2f5a8 to your computer and use it in GitHub Desktop.
薄いprotocol extensionを置いておくと簡単に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
import Foundation | |
import RealmSwift | |
protocol RealmStore { | |
typealias ResultType: Object | |
func getRealm() -> Realm | |
func allObjects() -> Results<ResultType> | |
func add(object: ResultType) | |
func findById(_: String) -> ResultType | |
func deleteAll() | |
} | |
extension RealmStore { | |
func getRealm() -> Realm { | |
let realm = try! Realm() | |
return realm | |
} | |
func allObjects() -> Results<ResultType> { | |
return getRealm().objects(ResultType) | |
} | |
func add(object: ResultType) { | |
let realm = getRealm() | |
try! realm.write { realm.add(object) } | |
} | |
func findById(id: String) -> ResultType { | |
let realm = getRealm() | |
return realm.objects(ResultType).filter(NSPredicate(format: "id = %@", id)).first! | |
} | |
func deleteAll() { | |
let realm = getRealm() | |
try! realm.write { | |
var array = [ResultType]() | |
realm.objects(ResultType).forEach { array.append($0) } | |
realm.delete(array) | |
} | |
} | |
} | |
class UserStore: RealmStore { | |
typealias ResultType = User | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment