Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store array in Realm object

Tags:

ios

orm

swift

realm

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?

like image 403
Dhvl B. Golakiya Avatar asked Jun 03 '15 06:06

Dhvl B. Golakiya


2 Answers

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

like image 103
Nykholas Avatar answered Nov 19 '22 07:11

Nykholas


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"]
    }
}
like image 31
Matt Pinkston Avatar answered Nov 19 '22 05:11

Matt Pinkston