Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare an array of Int in Realm Swift

Tags:

How can I declare an array of integers inside RLMObject?

Like :

dynamic var key:[Int]?

Gives the following error :

Terminating app due to uncaught exception 'RLMException', reason: ''NSArray' is not supported as an RLMObject property. All properties must be primitives, NSString, NSDate, NSData, RLMArray, or subclasses of RLMObject. See https://realm.io/docs/objc/latest/api/Classes/RLMObject.html for more information.'
like image 429
Vinicius Albino Avatar asked Feb 05 '16 19:02

Vinicius Albino


2 Answers

Lists of primitives are not supported yet unfortunately. There is issue #1120 to track adding support for that. You'll find there some ideas how you can workaround that currently.

The easiest workaround is create a object to hold int values. Then the model to have a List of the object.

class Foo: Object {
    let integerList = List<IntObject>() // Workaround
}

class IntObject: Object {
    dynamic var value = 0
}
like image 126
kishikawa katsumi Avatar answered Sep 20 '22 13:09

kishikawa katsumi


Fortunately arrays of primitive types are now supported in Realm 3.0 and above. (Oct 31 2017)

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!

class MyObject : Object {
    @objc dynamic var myString: String = ""
    let myIntArray = List<Int>()
}

Source: https://realm.io/blog/realm-cocoa-reaches-3-0/

like image 23
Philipp Otto Avatar answered Sep 19 '22 13:09

Philipp Otto