본문 바로가기
🍎 iOS

[RealmSwift] LinkingObjects와 Realm Studio

by 틴디 2022. 10. 2.
728x90
반응형

출처  : Realm  홈페이지

관계형 데이터베이스에서 테이블과 테이블간의 관계를 만들어 줄 수 있음

LinkingObjects를 사용하면 1:n, 1:1 관계를 만들어 줄 수 있음

class Customer: Object {
    @objc dynamic var idx = 0
    let products = List<Product>()
}
  • Object를 상속받는 모델 클래스에서 프로퍼티를 생성해 줌
  • array 타입으로서 Customer은 여러개의 Product를 가짐
  • Customer 객체에는 Product에 대한 참조가 생김
class Product: Object {
    @objc dynamic var name = ""
    @objc dynamic var price = 0

    let ofCustomer = LinkingObjects(fromType: Customer.self, property: "products")
    
    convenience init(_ name: String, _ price: Int) {
        self.init()
        self.name = name
        self.price = price
    }
}
  • LinkingObjects를 사용하여 백링크를 만들어 줌
  • 어떤 Customer에 현재 객체가 연결되었는지 알려줌

inUse

        let product1 = Product("나중에 구매할 상품 A", 2000)
        let product2 = Product("나중에 구매할 상품 B", 1500)
        let product3 = Product("나중에 구매할 상품 C", 600)
  • product 객체를 생성
        let customer = Customer()
        customer.idx = customer.incrementID()
        customer.type = .active // default 타입에 의해 선언하지 않아도 됨
        customer.products.append(objectsIn: [product1, product2, product3])
  • Product 타입의 products 프로퍼티에 객체들을 append시켜줌
        try! realm.write {
            realm.add(customer)
        }
  • realm에 write 해줌

 

RealmStudio로 객체 조회

Realm.Configuration.defaultConfiguration.fileURL
  • 실행될 코드 혹은 콘솔에서 fileURL을 얻을 수 있음. finder > 상단 네비게이션에서 '이동' > 폴더로 이동 후 나오는 창에서
  • 코드 실행해서 나오는 String의 file:// 뒤 문자열을 입력해줌

 

  • 기본으로 되어 있지만 더블 클릭 후 RealmStudio가 뜨지 않는다면 다음으로 열기를 이용해서 Realm Studio를 실행해 주면 됨

  • 객체를 조회하면 List<Product> 타입으로 지정한 products를 확인 할 수 있음 
  • 왼쪽 네비게이터에서 Products의 객체가 3개인 것을 확인 할 수 있는데, 이는 Product라는 객체가 생성되고 그 객체의 LinkingObjects는 Customer이며 Customer이 3개의 products를 가지고 있는 것. Customer과 Product가 1: n 으로 연결됨

 

  • 같은 코드를 2번 실행한 경우 Product를 3개씩 생성하고 Customer에 연결해 줬으므로, Product는 총 6개
        let allProduct = realm.objects(Product.self)
        print(allProduct)
        let allProduct = realm.objects(Product.self)
        print(allProduct.first?.ofCustomer)
Optional(LinkingObjects<Customer> <0x7fc783f10d30> (
	[0] Customer {
		idx = 1;
		privateType = 0;
		products = List<Product> <0x60000211c160> (
			[0] Product {
				name = 나중에 구매할 상품 A;
				price = 2000;
			},
			[1] Product {
				name = 나중에 구매할 상품 B;
				price = 1500;
			},
			[2] Product {
				name = 나중에 구매할 상품 C;
				price = 600;
			}
		);
	}
))
  • product 객체의 ofCustomer로 LinkingObjects로 연결한 Customer을 조회할 수 있음. 현재 Product 객체 중 첫번째 객체는 idx 를 1로 가지는 Customer 객체
        let allProduct = realm.objects(Product.self)
        print(allProduct[3].ofCustomer)
  • 4~6번째 조회된 Product 객체는 idx가 2인 Customer과 연결되어 있음. 콘솔로 확인하면 idx가 2로 찍히는 것을 확인할 수 있음

 

참고 및 출처 사이트

https://ali-akhtar.medium.com/crud-operation-using-realmswift-part-1-17a99de83cc1

 

>>> 틀리거나 이상한 점이 있다면 언제든 댓글 부탁드려요🙌🏻

728x90
반응형

댓글