4
1

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 1 year has passed since last update.

【SwiftUI】Realmを使ってみた

Posted at

はじめに

普段、ローカルデータベースを使うときはCoreDataを使うのですが、Realmを使う機会があったので記録しておきます。

実装

RealmEntity
import Foundation
import RealmSwift

public class RealmEntity: Object {
    @Persisted(primaryKey: true) public var id: Int = 0
}
RealmRepository
import Foundation
import RealmSwift

public protocol RealmRepositoryProtocol {
    func get() -> Results<RealmEntity>
    func add(_ bookmark: RealmEntity) throws
    func delete(_ bookmark: RealmEntity) throws
}

public final class RealmRepository: RealmRepositoryProtocol {
    let realm: Realm
    
    public init(realm: Realm = try! Realm()) {
        self.realm = realm
    }
    
    public func get() -> Results<RealmEntity> {
        realm.objects(RealmEntity.self)
    }
    
    public func add(_ bookmark: RealmEntity) throws {
        try realm.write {
            realm.add(bookmark)
        }
    }
    
    public func delete(_ bookmark: RealmEntity) throws {
        guard let bookmark = realm.object(ofType: RealmEntity.self, forPrimaryKey: bookmark.id) else {
            throw NSError(domain: "primary key not found", code: 0)
        }
        try realm.write {
            realm.delete(bookmark)
        }
    }
}
ContentView
import SwiftUI

struct ContentView: View {
    private let repository = RealmRepository()
    var body: some View {
        VStack(spacing: 50) {
            Button {
                print(Array(repository.get()))
            } label: {
                Text("取得")
            }
            
            Button {
                let realmEntity = RealmEntity()
                realmEntity.id = 0
                try? repository.add(realmEntity)
            } label: {
                Text("保存")
            }
            
            Button {
                let realmEntity = RealmEntity()
                realmEntity.id = 0
                try? repository.delete(realmEntity)
            } label: {
                Text("削除")
            }
        }
    }
}

おわり

CoreDataより数倍簡単でした。
今度からRealmを使おうと思います。

4
1
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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?