将数组存储在Realm对象中

时间:2015-06-03 06:54:45

标签: ios swift orm realm

我是Swift中的Realm新手。有没有办法在Realm Object中存储字符串数组?

我有一个JSON对象,如:

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

如何在权限键中存储消息数组?

3 个答案:

答案 0 :(得分:12)

你可以这样:

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()
}

无论如何,我认为现在已在Realm Swift Documentation

中详细记录

答案 1 :(得分:3)

如果你确定你的字符串可以安全地被标记化,这是一个不需要List<T>的简单技术。

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

答案 2 :(得分:-6)

此问题已由某人回答,请检查this link

您当前需要一个包含字符串的RLMObject:

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

@implementation StringObject
@end

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