본문 바로가기
DataBase/IOS - Realm

IOS) Realm - CRUD Operation & Notification - 1

by 후르륵짭짭 2021. 12. 4.
728x90
반응형

 

안녕하세요!

후르륵짭짭입니다.

이번에는 사내에서 사용하는 DB 사용법에 대해 설명하도록 하겠습니다.

(참고로, RealmSwiftf를 대상으로 설명합니다.)

Realm은 ORM(Object Relational Mapping)인데,,, 이것의 대한 설명은 나중에 다루도록 하겠습니다.

 

** 잡소리 **

저는 Realm 부분을 좀더 집중적으로 다루고 싶어서 카테고리를 뺐습니다.

앱 개발을 하다보니,,, 정말 쉽지 않습니다...

DB , Security , Operation,,, 등등 공부할게 많네요,,,,

하 보안,,,, 이것도 쫌 알아야 개발자라 할 수 있을 것 같아서,,,

일단 DB에 대한 설명은 나중에 좀 더 깊게 다루도록 하겠습니다.

CoreData 와 Realm,,, 그리고 SQLite 

그리고 ORM vs SQL 이런 것도 적도록 하겠습니다.

내용이 방대하여,,, 그냥 코드 위주로 적도록 하겠습니다.

요즘에 일이 많아서, 블로그 작성하는 것도 쉽지 않네요 ㅠㅠ

 

** REALM 객체 만들기 **

Realm은 ORM(Object Relation Mapping) 기술 입니다. 

자바에서는 JPA가 있는데,

MySQL은 테이블을 만들고 거기에 Key Value를 작성하는데,

Realm은 객체가 테이블이고 인스턴스 변수가 테이블에 들어가는 Key 값이 됩니다.

 

 - TODO -

class Todo : Object {

    @objc dynamic var name = "" //테이블 변수 설정
    @objc dynamic var details = "" //테이블 변수 설정
    
    let ofUser = LinkingObjects(fromType : User.self , property: "todos")
    //Relation된 객체 확인 - inverse

    convenience init(_ name : String ,_ details : String) {
        self.init()
        self.name = name
        self.details = details
    }

}

 

- User - 

class User : Object { // Realm 객체인 Object 상속

    @objc dynamic var firstName = ""
    @objc dynamic var userId = 0
    @objc dynamic var passport : Passort? // ONE to One 구조
    @objc private dynamic var privateUserType : Int = UserType.none.rawValue //ENUM CASE는 RawValue로 넣어줘야한다.
    let isEmailSubscriptionEnable = RealmProperty<Bool?>() //RealmOptional과 동일
    let todos = List<Todo>() // ONE To Many 구조 이다.

    var isUserHasTodos : Bool {
        return todos.count > 0
    }

    var type : UserType {
        get {return UserType(rawValue: privateUserType)!}
        set {privateUserType = newValue.rawValue}
    }

    //대상을 좀더 빠르게 찾아준다.
    override static func indexedProperties() -> [String] {
        return ["userId" , "firstName"]
    }

    //기준키가 된다.
    override static func primaryKey() -> String? {
        return "userId"
    }

    override static func ignoredProperties() -> [String] {
        return []
    }

    convenience init(_ firstName : String , _ userId : Int) {
        self.init()
        self.firstName = firstName
        self.userId = userId
    }

}

 

- Passport - 

class Passort : Object {
    @objc dynamic var passportNumber = ""
    @objc dynamic var expiryDate = Date.distantFuture

    let ofUser = LinkingObjects(fromType : User.self , property : "passport")
    //passport라는 프로퍼티에 현재 연결된 객체를 찾아준다.

    convenience init(_ passportNumber : String) {
        self.init()
        self.passportNumber = passportNumber
    }
}

 

** Create ** 

func createRealmObject(name : String , id : Int ) -> User{

        let realm = try! Realm()
//        print(realm.isEmpty)
        let userPassport = Passort("pass\(id)")

        let todo1 = Todo("RxSwift", "Need to create RxSwift blog")
        let todo2 = Todo("RxSwift - VIPER", "Need to create RxSwift with VIPER Blog")
        let todo3 = Todo("RxSwift-MVVM", "Need to create RxSwift with MVVM blog")

        let user = User(name, id)
        user.passport = userPassport
        user.isEmailSubscriptionEnable.value = nil //RealmProperty값 설정 방법
        user.todos.append(objectsIn:[todo1, todo2, todo3])
        user.type = UserType.gold
        
        try! realm.write({
            realm.add(user)
        })

        return user
  }

 

** Read **

func fetchRealm(){

        print(Realm.Configuration.defaultConfiguration.fileURL)

        let realm = try! Realm()
        let living = realm.objects(User.self)
        print(living.count)

        living.forEach { user in
            print(user.firstName)
            print(user.passport?.passportNumber)
            print(user.todos.count)
            print(user.passport?.ofUser.first?.firstName)

            print("========NEXT==========")
        }

        let living1 = realm.object(ofType: User.self, forPrimaryKey: 1) //하나만 찾아서 알려준다
        //PrimaryKey는 INt STRING이 될 수 있다.

        print(living1?.firstName)
        print(living1?.passport?.passportNumber)
        print(living1?.todos.count)
        print(living1?.passport?.ofUser.first?.firstName)

            print("========NEXT==========")

    }

 

** Update ** 

func updateRealmObject(){
        //REALM에서 프라이머리키를 변경하려면 삭제후에 넣어줘야한다.
        let realm = try! Realm()
        let user = realm.object(ofType: User.self, forPrimaryKey: 1)!
        print("Before",user.firstName)
        try! realm.write({
            user.firstName = "ali updated name"
        })

        print("After" ,user.firstName)

    }

 

** Delete ** 

func deleteRealmObject(){

        let realm = try! Realm()
        try! realm.write({
//            realm.delete(realm.objects(User.self).filter("firstName == 'ali new User'"))
            realm.deleteAll()
        })

    }

 

참고 사이트 : 

https://academy.realm.io/kr/section/apple/

 

Realm 아카데미의 iOS 특화 컨텐츠

Oops something went wrong You will not be receiving an email shortly with details on your subscription

academy.realm.io

https://medium.com/flawless-app-stories/crud-operation-using-realmswift-part-1-17a99de83cc1

 

CRUD Operation Using RealmSwift Part 1

In this part we will Cover

medium.com

https://docs.mongodb.com/realm-legacy/docs/swift/latest/index.html#models

 

Realm: Create reactive mobile apps in a fraction of the time

Oops something went wrong You will not be receiving an email shortly with details

docs.mongodb.com

https://stackoverflow.com/questions/38522285/update-realm-primary-key-value-swift

 

Update Realm primary key value swift

Im using Realm for my iOS app and for a table i have a primary key "name" let application = Application() application.domain = app.domain application.

stackoverflow.com

https://academy.realm.io/posts/nspredicate-cheatsheet/

 

NSPredicate Cheatsheet

Oops something went wrong You will not be receiving an email shortly with details on your subscription

academy.realm.io

https://ali-akhtar.medium.com/realm-notifications-realmswift-part-2-60c66ab99ea9

 

Realm Notifications (RealmSwift Part 2)

This is the continuation of the previous part . If you know the basics of CRUD operation in Realm you can continue this.

ali-akhtar.medium.com

https://stackoverflow.com/questions/41819435/realm-notification-token-on-background-thread

 

Realm notification token on background thread

I was trying to fetch realm data on the background thread and add a notification block (iOS, Swift). Basic example: func initNotificationToken() { DispatchQueue.global(qos: .backgrou...

stackoverflow.com

https://stackoverflow.com/questions/40493495/whats-the-difference-between-realm-write-and-realm-beginwriterealm-commitwrite

 

What's the difference between realm.write and realm.beginWrite+realm.commitWrite?

There are two ways of performing a write transaction in Realm, what's the difference between them? 1. try! realm.write { ... } 2. realm.beginWrite() ... try! realm.commitWrite()

stackoverflow.com

https://medium.com/flawless-app-stories/static-vs-dynamic-dispatch-in-swift-a-decisive-choice-cece1e872d

 

Static vs Dynamic Dispatch in Swift: A decisive choice

Performance vs Flexibility

medium.com

 

728x90
반응형

댓글