Storing an array of strings using Realm's RLMArray

前端 未结 5 2136
天命终不由人
天命终不由人 2020-12-14 03:48

Does anyone know how you can use Realm to store an array of strings? I\'m trying to map the following response into Realm correctly:

\"zoneInfo\": {
    \"ta         


        
5条回答
  •  既然无缘
    2020-12-14 04:31

    Cross posting from the github issue response: Although this example demonstrates how to store flat arrays of strings on a Realm model, you can extend this pattern to store anything from arrays of integers to native Swift enum's. Basically anything that you can map to a representable type in Realm.

    class RealmString: Object {
        dynamic var stringValue = ""
    }
    
    class Person: Object {
        var nicknames: [String] {
            get {
                return _backingNickNames.map { $0.stringValue }
            }
            set {
                _backingNickNames.removeAll()
                _backingNickNames.appendContentsOf(newValue.map({ RealmString(value: [$0]) }))
            }
        }
        let _backingNickNames = List()
    
        override static func ignoredProperties() -> [String] {
            return ["nicknames"]
        }
    }
    
    // Usage...
    
    let realm = try! Realm()
    try! realm.write {
        let person = Person()
        person.nicknames = ["John", "Johnny"]
        realm.add(person)
    }
    
    for person in realm.objects(Person) {
        print("Person's nicknames: \(person.nicknames)")
    }
    
    // Prints:
    // Person's nicknames: ["John", "Johnny"]
    

提交回复
热议问题