Reputation: 291
I have a SQL Database on Azure and I would like to synchronize it with Realm, for my iOS App (in Swift) For that, I have created a REST API which generates a JSON and now I would like to integrate this JSON in Realm. To do that, I have tried to follow the explanation on Realm Documentation, so now I have :
Realm Table :
class tbl_test: Object {
dynamic var id:Int = 0
dynamic var name:String = ""
override class func primaryKey() -> String? {
return "id"
}
}
Swift Code :
let realm = try! Realm()
let stringTxt:String = "[{\"id\": 1, \"name\": \"My Name\"}]"
var myData = NSData()
if let dataFromString = stringTxt.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
let jsonData = JSON(data: dataFromString)
if let encryptedData:NSData = try! jsonData.rawData() {
myData = encryptedData
}
}
try! realm.write {
let json = try! NSJSONSerialization.JSONObjectWithData(myData, options: NSJSONReadingOptions())
realm.create(tbl_test.self, value: json, update: true)
}
I use SwiftyJSON to convert my string to JSON.
When I run the program, I have this error message :
[__NSCFDictionary longLongValue]: unrecognized selector sent to instance 0x7fdcc8785820 2016-07-06 10:25:30.090 mydrawing[9436:2732447] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary longLongValue]: unrecognized selector sent to instance 0x7fdcc8785820'
Is it a good way to import JSON in Realm ? There is no official way according to what I have found, but this method should work...
Upvotes: 4
Views: 1602
Reputation: 18308
The problem you're facing is that the structure of the data you're passing to Realm.create(_:value:update:)
doesn't match what the method expects. It expects either a dictionary with keys corresponding to the managed properties on your model type, or an array with one element for each managed property.
After deserializing the JSON data, json
looks like so:
(
{
id = 1;
name = "My Name";
}
)
That is an array containing a single element that is an dictionary. When you pass this array to Realm.create(_:value:update:)
, Realm expects the first element of the array to be the value to use as the id
property on your tbl_test
type.
I suspect that what you mean to do is to call Realm.create
on each of the elements of the array in turn, instead of calling it on the array itself.
Upvotes: 2