본문 바로가기
DataBase/IOS - Realm

IOS)Realm - Configuration & Extension Realm Share - 1

by 후르륵짭짭 2022. 2. 13.
728x90
반응형

 

안녕하세요! 후르륵짭짭입니다.

얼릉 Realm에 대해서 작성해야하는데,,,

너무 작성하기 쉽지 않네요 ㅠㅠ 

일도 많고,,, 공부도 해야하고,,, 살려줘 ㅠㅠ 

 

** Configuration ** 

Configuration => 시스템 구성

Realm을 생성할 때 어느 위치에 Realm을 저장할 건지 설정 할 수 있습니다.

그런데 프로젝트를 시작 할 때 마다 Configuration을 매번 작성 할 때가 있습니다.

즉, 공통으로 가져가는 Realm은 파일로 만들고 공통적으로 사용하는 겁니다.

 

 - Default Realm 찍어보기 - 

func realmLocation(){
        print(#function)
        guard let realm = try? Realm() else {return}
        print(realm.configuration.fileURL!)
        print(realm.configuration.schemaVersion)
        print("==========================")
    }
    
//결과
file:///Users/taesooyoon/Library/Developer/CoreSimulator/Devices/48103AEA-4A40-4AA1-B304-1766D4547117/data/Containers/Data/Application/4EC9D722-9FAA-4721-942A-9A43C5DEDFF7/Documents/default.realm
0

 

 - Realm 객체 생성 - 

class Airport : Object{
    @objc dynamic var airport : String = ""
    @objc dynamic var model : String = ""
    @objc dynamic var userId : Int = 0
    
    convenience init(airport : String, model : String, userId : Int) {
        self.init()
        self.airport = airport
        self.model = model
        self.userId = userId
    }
    
    static override func primaryKey() -> String? {
        return "userId"
    }
}

 

 - FileSystem의 URL 반환하기 - 

func inLibrarayFolder(fileName : String) -> URL {
        //allDomainMask - "/Users/taesooyoon/Library/Developer/CoreSimulator/Devices/48103AEA-4A40-4AA1-B304-1766D4547117/data/Containers/Data/Application/8AF0F793-DBE6-4DF8-A186-7988D0E84189/Library", "/Library", "/Network/Library", "/System/Library"

        //userDomainMask - "/Users/taesooyoon/Library/Developer/CoreSimulator/Devices/48103AEA-4A40-4AA1-B304-1766D4547117/data/Containers/Data/Application/D3124A1D-9B22-47C5-9B9A-815771A39A58/Library"

        //localDomainMask - /Library"

        //networkDomainMask - "/Network/Library"

        let libraryUserDomain = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)
        let makeFileUrl = URL(fileURLWithPath: libraryUserDomain[0], isDirectory: true)
        return makeFileUrl.appendingPathComponent(fileName)
    }

이것은 라이브러리폴더의 URL을 반환해주는 겁니다.

그리고 거기에 fileName을 추가해줍니다,

 -  PreDefine된 Realm 파일 생성 - 

func prebundleData(){
        print(#function)
        let configuration = Realm.Configuration(fileURL: inLibrarayFolder(fileName: "bundle.realm"))
        guard let realm = try? Realm(configuration: configuration) else {return}
        print(realm.configuration.fileURL!)
        print(realm.configuration.schemaVersion)
        print(realm.isEmpty)
        
        let airport1 = Airport(airport: "jinnah", model: "OKC", userId: 1)
        let airport2 = Airport(airport: "Steven", model: "NYC", userId: 2)
        
        try! realm.write({
            realm.add([airport1, airport2])
        })
        
        print(realm.configuration.fileURL!)
        
        print("==========================")
    }

위에 처럼 bundle.realm URL을 생성하고 나서 

Realm을 생성해줍니다 .

그러면 위에 처럼 Bundle.realm 파일이 생성이 됩니다.

이 Realm 파일을 이제 언제든지 공통적으로 사용하게 될 Bundle로 사용할 예정 입니다.

저 파일을 복사해서 이제 프로젝트에 넣어 줍니다 .

복사 할 때 잊지 말아야 할 것이 Target을 설정해줘야합니다.

 

- 새로운 Main 파일 생성 -

이 Main 파일은 앞으로 꾸준히 사용할 Realm 파일입니다.

Bundle.Realm은 기본적으로 탑재가 된 것이고 

Main은 사용자의 정보나 본격적인 Realm 파일 입니다.

func makeMainRealmFile(){
        print(#function)
        let configuration = Realm.Configuration(fileURL: inLibrarayFolder(fileName: "main.realm"))
        guard let realm = try? Realm(configuration: configuration) else {return}
        print(configuration.fileURL!)
        
        let airport1 = Airport(airport: "London", model: "LOD", userId: 3)
        let airport2 = Airport(airport: "Seoul", model: "SEL", userId: 4)
        
        try! realm.write({
            realm.add([airport1,airport2])
        })
        
        print("==========================")
    }

위에 처럼 생성을 해줍니다.

 

 - Bundle.Realm 파일을 그대로 Main으로 복사하기 (Main.Realm 생성 - 1 ) - 

func createMainRealmWithCopyBundle(){
        print(#function)
        let main2RealmURL = inLibrarayFolder(fileName: "main2.realm")
        if let bundleUrl = Bundle.main.url(forResource: "bundle", withExtension: "realm") {
            if !FileManager.default.fileExists(atPath: main2RealmURL.path) {
                try! FileManager.default.copyItem(at: bundleUrl, to: main2RealmURL)
                print(main2RealmURL)
            }
        }
        print("==========================")
    }

 

 - Bundle.Realm 파일을 그대로 Main으로 복사하기 (Main.Realm 생성 - 2 ) -

    func addPreDefineDataToMainRealm(){
        print(#function)
        let configurationMain = Realm.Configuration(fileURL: inLibrarayFolder(fileName: "main.realm"))
        let realmMain = try! Realm(configuration: configurationMain)
        
        let BundleFileURL = Bundle.main.url(forResource: "bundle", withExtension: "realm")
        let configurationBundle = Realm.Configuration(fileURL: BundleFileURL)
        let realmBundle = try! Realm(configuration: configurationBundle)
        
        if true {
            var needsToCopy = [Airport]()
            for obj in realmBundle.objects(Airport.self){
                let airports = realmMain.objects(Airport.self).filter { airport in
                    return airport.userId == obj.userId
                }
                
                if airports.isEmpty {needsToCopy.append(obj)}
            }
            
            if !needsToCopy.isEmpty {
                try! realmMain.write({
                    for airport in needsToCopy{
                        realmMain.create(Airport.self, value: airport, update: .all)
                        //2개 이상의 Realm을 동시에 사용 할 때
                        //Realm 값을 변경해야한다면 Add는 사용 할 수 없고
                        //Create로 업데이트 해줘야한다.
                    }
                })
            }
        }
        
        print("==========================")
    }

하지만 위에 같은 방식은 realmMain.add()로 하면 안 됩니다.

두개의 Realm을 동시에 사용 할 때는 위에 같이 create로 해줘야 한다.

이때 realm.create(추가할 객체 , 값 , 수정여부)

로 처리 해주면 된다.

 

** Reference **

https://ali-akhtar.medium.com/realm-custom-configuration-and-encryption-realmswift-part-3-f991f090ae22

 

Realm Custom Configuration and Encryption (RealmSwift Part 3)

In this part we will cover following topics

ali-akhtar.medium.com

https://github.com/aliakhtar49/RealmBlog/blob/master/PreBundleDataRealm/PreBundleDataRealm/ViewController.swift

 

GitHub - aliakhtar49/RealmBlog

Contribute to aliakhtar49/RealmBlog development by creating an account on GitHub.

github.com

 

- Configuration - 

https://stackoverflow.com/questions/47193169/realm-object-is-already-managed-by-another-realm

 

Realm , Object is already managed by another Realm

Use realm to save data. Config the realm use defaultconfig. then , I addOrUpdate some RLMModels It's success. I changed the config use RLMRealmConfiguration *config = [RLMRealmConfiguration

stackoverflow.com

https://github.com/Tedigom/Swift/blob/master/additional_topics/autoreleasepool.md

 

GitHub - Tedigom/Swift: Swift Self-study

Swift Self-study. Contribute to Tedigom/Swift development by creating an account on GitHub.

github.com

https://github.com/realm/realm-cocoa/blob/master/examples/ios/swift/Encryption/ViewController.swift

 

GitHub - realm/realm-cocoa: Realm is a mobile database: a replacement for Core Data & SQLite

Realm is a mobile database: a replacement for Core Data & SQLite - GitHub - realm/realm-cocoa: Realm is a mobile database: a replacement for Core Data & SQLite

github.com

 

- share - 

https://academy.realm.io/posts/tutorial-sharing-data-between-watchkit-and-your-app/

 

Sharing Data Between WatchKit and your App with Realm

Today’s blogpost is contributed by one of our users: Andrea Mazzini, and originally appeared on his blog. Andrea is cofounder and iOS developer at Fancy Pixel, an Italian company building web and mobile apps for iOS and Android. You can find Andrea on Gi

academy.realm.io

https://github.com/aliakhtar49/RealmBlog/blob/master/PreBundleDataRealm/Podfile

 

GitHub - aliakhtar49/RealmBlog

Contribute to aliakhtar49/RealmBlog development by creating an account on GitHub.

github.com

https://gwangyonglee.tistory.com/63

 

Podfile Syntax - inherit!이란

유닛테스트 환경 설정 도중 과 같은 에러를 만났다. 테스트 타겟에서 해당 모듈(Firebase)을 가져올 수 없다는 메시지이다. 테스트 타겟에서 부모 타겟에 있는 모듈들의 상속에 대한 이슈이다. 그

gwangyonglee.tistory.com

 

728x90
반응형

댓글