29
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Realm Swiftを簡単に使うためのDAO実装サンプル(iOS)

Last updated at Posted at 2017-03-10

Realm java 3.0が出たとのことなので、もともと簡単に利用出来るRealmを
私的にもっと簡単に使えるのではないか、と思えるDAOをiOS(iosのRealmはまだ2系)で作ってみました。

##DAO

DAO

import Foundation
import RealmSwift

class RealmBaseDao <T : RealmSwift.Object> {
    let realm: Realm
    
    init() {
        try! realm = Realm()
    }
    
    /**
     * 新規主キー発行
     */
    func newId() -> Int? {
        guard let key = T.primaryKey() else {
            //primaryKey未設定
            return nil
        }
        
        if let last = realm.objects(T.self).last as? RealmSwift.Object,
            let lastId = last[key] as? Int {
            return lastId + 1
        } else {
            return 1
        }
    }
    
    /**
     * 全件取得
     */
    func findAll() -> Results<T> {
        return realm.objects(T.self)
    }
    
    /**
     * 1件目のみ取得
     */
    func findFirst() -> T? {
        return findAll().first
    }
    
    /**
     * 指定キーのレコードを取得
     */
    func findFirst(key: AnyObject) -> T? {
        return realm.object(ofType: T.self, forPrimaryKey: key)
    }
    
    /**
     * 最後のレコードを取得
     */
    func findLast() -> T? {
        return findAll().last
    }
    
    /**
     * レコード追加を取得
     */
    func add(d :T) {
        do {
            try realm.write {
                realm.add(d)
            }
        } catch let error as NSError {
            print(error.description)
        }
    }

    /**
    * T: RealmSwift.Object で primaryKey()が実装されている時のみ有効
    */
    func update(d: T, block:(() -> Void)? = nil) -> Bool {
        do {
            try realm.write {
                block?()
                realm.add(d, update: true)
            }
            return true
        } catch let error as NSError {
            print(error.description)
        }
        return false
    }

    /**
     * レコード削除
     */
    func delete(d: T) {
        do {
            try realm.write {
                realm.delete(d)
            }
        } catch let error as NSError {
            print(error.description)
        }
    }
    
    /**
     * レコード全削除
     */
    func deleteAll() {
        let objs = realm.objects(T.self)
        do {
            try realm.write {
                realm.delete(objs)
            }
        } catch let error as NSError {
            print(error.description)
        }
    }

}

##使い方

使い方
import Foundation
import RealmSwift

//Realm Object
class SampleObject: Object {

    dynamic var id = 0
    dynamic var created = NSDate()

    override static func primaryKey() -> String? {
        return "id"
    }
}

class SampleObjectViewModel {
    var id = 0
    var created = NSDate()
    var description:String {
        return "\(id)," + created.description
    }

    //RealmBaseDao<Realm Objectクラス>で、基本的なことができる
    static let dao = RealmBaseDao<SampleObject>()

    init(sampleObject:SampleObject) {
        id = sampleObject.id
        created = sampleObject.created
    }

    static func load() -> [SampleObjectViewModel] {
        let objects = dao.findAll()
        return objects.map { SampleObjectViewModel(sampleObject: $0) }
    }

    static func create() -> SampleObjectViewModel {
        let object = SampleObject()
        object.id = dao.newId()!
        dao.add(d: object)
        let viewModel = SampleObjectViewModel(sampleObject:object)
        return viewModel
    }

    func update() {
        let dao = type(of: self).dao
        guard let object = dao.findFirst(key: id as AnyObject) else {
            return
        }
        object.created = created
        let _ = dao.update(d: object)
    }

    func delete() {
        let dao = type(of: self).dao
        guard let object = dao.findFirst(key: id as AnyObject) else {
            return
        }
        dao.delete(d: object)
    }
}
29
31
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?