Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store array of strings into Realm instance using a Dictionary?

Tags:

swift3

realm

I am new to Realm and having this issue.

I am having a Dictionary like this

{
    firstName : "Mohshin"
    lastName : "Shah"
    nickNames : ["John","2","3","4"]              
}

and a class like this

class User: Object {
    var firstName: String?
    var lastName: String?
    var nickNames: [String]?
}

While I am trying to insert values it is throwing an exception as below

Property 'nickNames' is declared as 'NSArray', which is not a supported RLMObject property type. All properties must be primitives, NSString, NSDate, NSData, NSNumber, RLMArray, RLMLinkingObjects, or subclasses of RLMObject.
See https://realm.io/docs/objc/latest/api/Classes/RLMObject.html for more information.
I have also tried

var nickNames =  NSArray()

var nickNames =  NSMutableArray()

But not working.Do I need to make the Nickname model class and create a property as follow or there's a way to do this ?

var nickNames =  List<Nickname>()
like image 451
Mohshin Shah Avatar asked Feb 21 '17 07:02

Mohshin Shah


2 Answers

UPDATE:

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.

Lists of primitive values work much the same way as lists containing objects, as the example below demonstrates for Swift:

class Student : Object {
    @objc dynamic var name: String = ""
    let testScores = List<Int>()
}

// Retrieve a student.
let realm = try! Realm()
let bob = realm.objects(Student.self).filter("name = 'Bob'").first!

// Give him a few test scores, and then print his average score.
try! realm.write {
    bob.testScores.removeAll()
    bob.testScores.append(94)
    bob.testScores.append(89)
    bob.testScores.append(96)
}
print("\(bob.testScores.average()!)")   // 93.0

All other languages supported by Realm also supports lists of primitive types.

like image 131
bmunk Avatar answered Sep 20 '22 08:09

bmunk


you can find more details here. https://academy.realm.io/posts/realm-list-new-superpowers-array-primitives/

class BlogPost: Object {
  @objc var title = ""
  let tags = List<String>()

  convenience init(title: String, tag: String) {
    self.init()
    self.title = title
    self.tags.append(tag)
  }
}

more details here

like image 27
Rushikesh Reddy Avatar answered Sep 24 '22 08:09

Rushikesh Reddy