Store array in Realm object

10,383

Solution 1

You could something like:

class Messages: Object {
    dynamic var message = ""
}

class Permission: Object {
    let messages = List<Messages>()
}

class Person: Object {
    dynamic var firstName = ""
    dynamic var imgName = ""
    dynamic var lastName = ""
    var permissions : Permission = Permission()
}

Anyways, I think now is well documented in Realm Swift Documentation

Solution 2

Here's one simple technique that doesn't require List<T> if you're sure your strings can be safely tokenized.

class Person: Object {
    private let SEPARATOR = "||"

    dynamic var permissionsString: String? = nil
    var permissions: [String] {
        get {
            guard let perms = self.permissionsString else { return [] }
            return perms.componentsSeparatedByString(SEPARATOR)
        }
        set {
            permissionsString = newValue.count > 0 ? newValue.joinWithSeparator(SEPARATOR) : nil
        }
    }

    override static func ignoredProperties() -> [String] {
        return ["permissions"]
    }
}
Share:
10,383

Related videos on Youtube

Dhvl B. Golakiya
Author by

Dhvl B. Golakiya

Updated on June 04, 2022

Comments

  • Dhvl B. Golakiya
    Dhvl B. Golakiya almost 2 years

    I'm new to Realm in Swift. Is there any way to store an array of strings in Realm Object?

    I have a JSON Object like:

    "firstName": "John",
    "imgName": "e9a07f7d919299c8fe89a30022151135cd63773f.jpg",
    "lastName": "Wood",
    "permissions": {
        "messages": ["test", "check", "available"]
    },
    

    How can I store messages array in permissions key?