Skip to content

Instantly share code, notes, and snippets.

@ainame ainame/RealmStore.swift Secret
Created Feb 7, 2016

Embed
What would you like to do?
薄いprotocol extensionを置いておくと簡単にrealmが触れるモデルが出来上がって便利
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
You can’t perform that action at this time.