2017-12-05 9 views
0

스위프트 4 영역 루프 일반 및 재사용 확인 여기에 9.2엑스 코드, 스위프트

몇 가지 영역 클래스는 내가 가지고있다 이 위대한 작품을

let remoteDogs = remoteRealm.objects(Dog.self) 

for remoteDog in remoteDogs{ 
    if let localDog = realm.objects(Dog.self).filter("id = %@",remoteDog.id).first{ 
    // Update 
    if localDog.updated < remoteDog.updated{ 
     //Remote is newer; replace local with it 
     realm.create(Dog.self, value: remoteDog, update:true) 
    } 
    } 
} 

,하지만 전체 롤빵에이 같은 물건을 수행해야합니다 영역은 특정 Dog 클래스와 객체를 생성하고 내가 가지고있는 영역 강의들. 그래서 나는이 같은 좀 더 일반적인 만들려고 노력 해요 : 작품의

let animals = [Dog.self, Cat.self, Horse.self] 

for animal in animals{ 
    let remoteAnimals = remoteRealm.objects(animal) 

    for remoteAnimal in remoteAnimals{ 
    if let localAnimal = realm.objects(animal).filter("id = %@",remoteAnimal.id).first{ 
     // Update 
     if localAnimal.updated < remoteAnimal.updated{ 
     //Remote is newer; replace local with it 
     realm.create(animal, value: remoteAnimal, update:true) 
     } 
    } 
    } 
} 

이런 종류의,하지만 언제 내가 (remoteAnimal.idremoteAnimal.updated와 같은) 객체의 속성을 참조 할 것이 아무튼 때문에 다음 컴파일러는 불평 어떤 종류의 물체가 remoteAnimal인지 알지 못합니다.

누구나 전에 이렇게 해본 적이 있습니까? 모든 렐름 클래스에 대해이 동일한 코드를 반복해서 작성할 필요가 없도록 어떻게 할 수 있습니까? 감사!

+1

여기서 문제는'realm.objects (T.self가)의'가' 결과'와 animals''의 유형 [Object.Type]''입니다 반환 것입니다 : 여기에 놀이터입니다. 이것은'animals'의 모든 요소에 대해 가장 가까운 공통 부모가'Object'이기 때문입니다. 조쉬의 대답은 : 모든 세 객체가'Animal'으로부터 상속받은 경우,'animals'는'[Animal.Type]'타입을 가질 것이고, 컴파일러는'localAnimal'을위한 동물을 정확하게 되돌려 주어야합니다. –

답변

2

영역 객체는 id 또는 을 업데이트하지 않았습니다. Cat 및 Horse 클래스는 Object 서브 클래스 인 Animal 클래스에서 상속되며 id 또는 으로 업데이트됩니다. 이러한 속성은 Animal에 정의되어 있으므로 모든 하위 클래스 (Dog, Cat, Horse)에서 사용할 수 있습니다. 당신은 또한 목적 C의 NSObject setValue:forKey:을 남용 할 수

class Animal: Object { 
    @objc dynamic var id = UUID().uuidString 
    @objc dynamic var updated = Date() 
    //Other properties... 
} 

class Dog: Animal { 
    //Other properties... 
} 

EDIT 이름으로 속성을 설정합니다. 이것은 매우 조잡한 타이핑이고 좋은 객체 지향 디자인은 아니지만 작동합니다.

import UIKit 

class A: NSObject { 
    @objc var customProperty = 0 
} 
let a = A() 
a.setValue(5, forKey: "customProperty") 
print(a.customProperty) 
+0

방금 ​​클래스 정의를 추가했습니다. –

+0

위대한 작품입니다. 고맙습니다! –