IOS

[IOS] Realm Database CRUD 사용해보기

Xmobile 2020. 10. 17. 17:40

 

Realm Swift를 이용하면 효율적으로 안전하고 빠르고 지속적인 방법으로 앱의 모델 레이어를 작성할 수 있습니다.

https://realm.io/kr/docs/swift/latest/

 

Realm: 리액티브 모바일 애플리케이션을 손쉽고 빠르게 만드세요

Realm Swift is the first database built for mobile. An alternative to SQLite and Core Data that's fast, easy to use, and open source.

realm.io

의존성 설정 

pod 'RealmSwift', '~> 3.20.0'

 

사용해 보기 

1. entity 클래스 

import Foundation
import RealmSwift

class LottoEntity: Object {
    @objc dynamic var lottoid: Int = 0
    @objc dynamic var desc = ""
    @objc dynamic var url = ""
    @objc dynamic var regDate: Double = 0.0
    @objc dynamic var modDate: Double = 0.0
    
    override static func primaryKey() -> String? {
        return "lottoid"
    }
}

2. crud 만들기

import Foundation
import RealmSwift

public class DatabaseManager {
    static let shared = DatabaseManager()
    private var realm: Realm
    
    private init() {
        realm = try! Realm()
    }
    
    //id자동증가를 위한 함수 
    private func newID() -> Int {
        return realm.objects(LottoEntity.self).count+1
    }
    
    //삽입
    func insert(lottoEntity: LottoEntity) {
        lottoEntity.lottoid = newID()
        lottoEntity.regDate = Date().currentTimeMillis()
        
        try! realm.write {
            realm.add(lottoEntity)
        }
    }
    
    //업데이트 
    func update(lottoId: Int, desc: String?, url: String?) {
        let lottoEntity = selectById(lottoId: lottoId)
        if let workout = lottoEntity {
            try! realm.write {
                if let desc = desc{
                    workout.desc = desc
                }
                if let url = url{
                    workout.url = url
                }
                workout.modDate = Date().currentTimeMillis()
            }
        }
    }
    
    //삭제 object로 
    func delete(lottoEntity: LottoEntity) {
        try! realm.write {
            realm.delete(lottoEntity)
        }
    }
    
    //삭제 id로 
    func deleteById(lottiId: Int) {
        try! realm.write {
            if let entity = selectById(lottoId: lottiId) {
                realm.delete(entity)
            }
        }
    }
    
    //삭제 all
    func deleteAll() {
        try! realm.write {
            realm.deleteAll()
        }
    }
    
    //가져오기 id로 
    func selectById(lottoId: Int) -> LottoEntity? {
        let predicate = NSPredicate(format: "lottoid == %i", lottoId)
        return realm.objects(LottoEntity.self).filter(predicate).first
    }
    
    //가져오기 all
    func selectAll() -> Results<LottoEntity> {
        return realm.objects(LottoEntity.self)
    }
}

extension Date {
    func currentTimeMillis() -> Double {
        return Double(self.timeIntervalSince1970 * 1000)
    }
}

3. UNIT 테스트로 검증해보기  

func testExample() throws {
        //all 삭제
        DatabaseManager.shared.deleteAll()
        
        //insert
        var entity = LottoEntity()
        entity.url = "url"
        entity.desc = "desc"
        DatabaseManager.shared.insert(lottoEntity: entity)
        XCTAssert(DatabaseManager.shared.selectAll().count == 1)
        
        //update
        //desc 값 변경
        DatabaseManager.shared.update(lottoId: 1, desc: "desc_change", url: nil)
        print(DatabaseManager.shared.selectAll())
        if let selEntity = DatabaseManager.shared.selectById(lottoId: 1) {
            XCTAssert(selEntity.desc == "desc_change")
        }
        
        //insert
        entity = LottoEntity()
        entity.url = "url1"
        entity.desc = "desc2"
        DatabaseManager.shared.insert(lottoEntity: entity)
        XCTAssert(DatabaseManager.shared.selectAll().count == 2)
        
        //delete
        if let entity = DatabaseManager.shared.selectAll().first {
            DatabaseManager.shared.delete(lottoEntity: entity)
        }
        print(DatabaseManager.shared.selectAll())
        XCTAssert(DatabaseManager.shared.selectAll().count == 1)
        
        //delete all
        DatabaseManager.shared.deleteAll()
        XCTAssert(DatabaseManager.shared.selectAll().count == 0)
        print(DatabaseManager.shared.selectAll())
    }

하기와 같이 정상적으로 동작하는것을 확인해 보았습니다.