Storing an array of strings using Realm's RLMArray

前端 未结 5 2134
天命终不由人
天命终不由人 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:11

    The RealmString approach is good, but you end up with a new RealmString every time you update the values, leaving a ton of unused objects laying around if you don't clean them up.

    I would suggest using something like:

    fileprivate let separator = "\u{FFFF}"
    
    class Person: Object {
        fileprivate dynamic var _nicknames: String?
        var nicknames: [String] {
            get { return _nicknames?.components(separatedBy: separator) ?? [] }
            set { _nicknames = newValue.isEmpty ? nil : newValue.joined(separator: separator) }
        }
    
        override static func ignoredProperties() -> [String] {
            return ["nicknames"]
        }
    }
    
    0 讨论(0)
  • 2020-12-14 04:11
    extension String {
        func toStringObject() -> StringObject {
            return StringObject(initValue: self)
        }
    }
    
    extension Sequence where Iterator.Element == String {
        func toStringObjects() -> List<StringObject> {
            let list = List<StringObject>()
            for s in self {
                list.append(s.toStringObject())
            }
            return list
        }
    }
    
    extension Int {
        func toIntObject() -> IntObject {
            return IntObject(initValue: self)
        }
    }
    
    extension Sequence where Iterator.Element == Int {
        func toIntObjects() -> List<IntObject> {
            let list = List<IntObject>()
            for s in self {
                list.append(s.toIntObject())
            }
            return list
        }
    }
    
    0 讨论(0)
  • 2020-12-14 04:28

    For the Swift 3.0 here is the change (in my case the Xcode 8 compiler didn't offer auto fix when i switched to swift 3.0 so I had some pain to resolve it).

    _backingNickNames.append(objectsIn: newValue.map { RealmString(value: [$0]) })
    
    0 讨论(0)
  • 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<RealmString>()
    
        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"]
    
    0 讨论(0)
  • 2020-12-14 04:33

    UPDATE (most of the previous answers are no longer correct):

    You can now store primitive types or their nullable counterparts (more specifically: booleans, integer and floating-point number types, strings, dates, and data) directly within RLMArrays or Lists. If you want to define a list of such primitive values you no longer need to define cumbersome single-field wrapper objects. Instead, you can just store the primitive values themselves.

    Lists of primitive values work much the same way as lists containing objects, as the example below demonstrates for Swift:

    class Student : Object {
        @objc dynamic var name: String = ""
        let testScores = List<Int>()
    }
    
    // Retrieve a student.
    let realm = try! Realm()
    let bob = realm.objects(Student.self).filter("name = 'Bob'").first!
    
    // Give him a few test scores, and then print his average score.
    try! realm.write {
        bob.testScores.removeAll()
        bob.testScores.append(94)
        bob.testScores.append(89)
        bob.testScores.append(96)
    }
    print("\(bob.testScores.average()!)")   // 93.0
    

    All other languages supported by Realm also supports lists of primitive types.

    0 讨论(0)
提交回复
热议问题