简体   繁体   中英

Store array in Realm object

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?

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

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"]
    }
}

This question already answered by someone , Please check this link

You do currently need an RLMObject which contains the string:

@interface StringObject : RLMObject
@property NSString *value;
@end
RLM_ARRAY_TYPE(StringObject)

@implementation StringObject
@end

@interface Object : RLMObject
@property RLMArray<StringObject> *array;
@end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM