Skip to content

Instantly share code, notes, and snippets.

@DioGnDev
Created September 28, 2018 00:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DioGnDev/57637d75247682f9c1d947cffc6c2f67 to your computer and use it in GitHub Desktop.
Save DioGnDev/57637d75247682f9c1d947cffc6c2f67 to your computer and use it in GitHub Desktop.
helper for realm database using swift
//
// RealmManager.swift
// TestDOT
//
// Created by Ilham Hadi Prabawa on 7/23/18.
// Copyright © 2018 Ilham Hadi Prabawa. All rights reserved.
//
import Foundation
import RealmSwift
class RealmManager<T: Object> {
let realm: Realm
enum RealmResult{
case finished
}
init() {
realm = try! Realm()
print(Realm.Configuration.defaultConfiguration.fileURL!)
}
func addData(_ model: T, _ completion: @escaping(RealmResult) -> Void){
try! realm.write {
realm.add(model)
}
completion(.finished)
}
func addDatas(_ models: [T], _ completion: @escaping(RealmResult) -> Void){
try! realm.write {
for model in models{
realm.add(model)
}
}
completion(.finished)
}
func fetchObjects(_ model: T.Type, _ searchKey: String, _ id: Int ) -> [T?] {
let objs = realm.objects(model).filter("\(searchKey) == %@", String(describing: id))
return Array(objs)
}
func fetchObjects(_ model: T.Type) -> [T?] {
let objs = realm.objects(model)
return Array(objs)
}
func filterObjects(_ model: T.Type, _ searchKey: String, _ searchValue: String) -> [T?] {
let objs = realm.objects(model).filter("\(searchKey) CONTAINS %@", searchValue)
return Array(objs)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment