IOS: store a json with array and object nested - ios

I have a question about creating a database with core data.
In my app at first start I should parse some json to obtain some data to insert in core data db.
my json files are structured in this way: (I show only an element of my json)
[{"id":"s1",
"n":"Name hotel",
"id_loc":["l1","l2","l3","l4"],
"val":3,
"tel1":"12345678",
"tel2":"12345678",
"obj":
{"id":"o1",
"n":"Name",
"des":"description",
"flag":"red"}
}]
I understand that I can consider this as an entity in coredata and consider all element as attribute, it's clear.
Now you can see that inside my json there is an array "id_loc" and an object (or dictionary) "obj".
In core data what's the way to manage these two elements?
I suppose that "obj" can be managed as a new entity, and "id_loc", what's the way to set it in my core data DB?
Can you help me?
Thanks

For obj, it's as you suggest: create a new entity, and set up a relationship between the two entities.
For id_loc it depends on how you need to use the data.
If you just want to have that data available when you look up an instance (that is, you maybe display this data but don't ned to search for it), you can store the strings in an NSArray. Make the attribute transformable in the Core Data model editor, and Core Data will read/write the complete array.
If you need to look up data based on id_loc values (for example: Find every object where id_loc contains l3), the best approach is to create another entity to hold values of id_loc, and set up a to-many relationship to that new entity.

Related

Best way to save a dictionary containing bunch of Core Data objects?

I wish to save a dictionary containing some Core Data objects (bunch of different entities). The objects also have quite a few relationships (and inverse relationships) defined. What would be the best way to go about it?
I tried using NSKeyedArchiver and writing to a file. While that works great, when trying to read from the file using NSKeyedUnarchiver, it fails on one of the classes with the error
-[SomeEntity initWithCoder:]: unrecognized selector sent to instance
EDIT - More details
I have a bunch of objects, each having properties based on which they can be filtered. The properties are in themselves Core Data entity objects since they have a complex structure.
I wish to save the filters the user has selected so that the next time they view the objects, the objects can be filtered as per their previous selection.
Say there are 3 filters, Filter A, B and C and each can have 5 different values. Now the user might select Filter A1, A2, B1 and C3 (or a different combination). My question, how do I save these selected filters (A1, A2, B1 and C3 in this case) using Core Data?
Let me see if I understand your question: You have a collection of managedObjects that are already saved in a context. They may already be persisted in the SQL database. You want to save that collection ALSO to another file for other purposes. You have already considered saving the information of this collection inside core-data in some way and have already rejected it. You have also considered simply saving the query generation tokens to save the state of the database as it currently is, but that also is not what you want. The point is to have a file that contains a copy of some of the managedObjects organized in a way that you can get the data back without using the SQL database that was already designed exactly for that purpose.
Solution 1: Turn each managed object in a dictionary.
You can get every attribute and every property of every object by getting a managed object's entity and then accessing the attributesByName and
relationshipsByName property of the entity. From there you make a simple loop to put each property into a dictionary. I also suggest you store the objectID and point to the objectID when encoding the relationships. Then replace the managedObject in your dictionary with dictionary that contains all the attributes and relationship. This new dictionary should be easy to archive and unarchive.
This make sure that the data when you unarchive is exactly how you left it. When you unarchive you will get a COPY of data and if the managed objects have changed in your database since then, you will get the OLD values. Also these copies are not core-data object because they are unconnected to a managed Object Context.
Solution 2: Just save the Managed Object's ObjectId.
Replace every managed object in your collection with the object's objectId. This dictionary can be easily archived. When you unarchive it replace every objectId with a core data object (if found) using existingObjectWithID: on the context. If entities have been deleted then you won't get them back. If entities have changed then you will get the NEW values.
Solution 3: Don't do any of this
It seems to me that you may not be aware core-data are already saved in a database. If you have some collection of managedObjects, you should be able to recreated it from your database. If you aren't able to, then you should add properties and/or relationships that will allow you to so.
Try like this :
ARCHIVE :
NSDictionary *yourDictData = [NSDictionary dictionaryWithObject:json forKey:#"key"]; // This is for example. Here you have to replace ur dictionary
NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:yourDictData];
UNARCHIVE :
NSDictionary *myData = [NSKeyedUnarchiver unarchiveObjectWithData:yourDictData];

Saving an array of objects in Core Data swift 3

So I'm trying to take an array of objects that already exist and then persist the data using core data. I'm slightly confused if I need to map out all of the properties in that custom object, or if I can just save every object directly?
An example would be something like making an entity called CoreDataArrayObj, and then making the custom object an attribute? Or would I need to take that CoreDataArrayObj entity and make all of the properties within the custom object such as string1Prop: String, string2Prop: String, Int1Prop: Int etc...?

Writing a list of objects to realm

I just start thinking about implementing Realm and have some newbie doubts.
For example I receive a list of objects which I transform into realm objects. How can I write the whole list directly to Realm, without writing each object separately?
A typical workaround comes into my mind, which would be defining a bigger object which contains this list as a property and writing that bigger object to the DB. But is it possible to write directly the obtained list of objects to DB without something that encapsulates them?
And also when preparing this list of Realm objects, I basically have a list of dictionaries. What's the best approach into transforming all of them directly into a list of Realm objects?
Just to confirm. When you mention your list of objects at the top and then mention that you have a list of dictionaries, are they the same thing?
If they are, and your data is coming down as a set of dictionaries, as long as the key names match the properties in your Realm Object models, then you can simply loop through each dictionary and pass each one to Realm to create it as a new entry in the database:
let realm = try! Realm()
try! realm.write {
for dictionary in dictionaries {
realm.create(MyObject.self, value: dictionary, update: false)
}
}
More information on that API can be found on Realm Swift's documentation page.
If your objects don't map directly to the properties in your Realm file, then you're going to need to manually reformat the structure of your list of objects until either could be inserted as a dictionary, or you can manually create your own Realm Object instances off them.

CoreData Unique: Decide update or create

I'm using CoreData in my project and I'm thinking about unique fields and creating objects or updating them if they are already existing.
UseCase:
Get JSON from Server
Map JSON to Object
Save to CoreData
What I want to do is:
Get JSON from Server
Map JSON to Object
Does the object already exists (Unique field is unique identifier for object)
If YES
Get object
Update fields
If NO
Create object
Save to CoreData
Isn't that a lot overhead for the solution? So every time I get an object I have to check the CoreData. Is there something that can do this handeled by CoreData internally?
Have a look a MagicalRecord it has built in maps from JSON to core data and will keep unique items unique.

RestKit 0.20 and ManagedObjectContexts

I am mapping data using RestKit 0.20 into a Core Data and displaying it in a UITable. I am writing the data, an 'Activity' object, to the mainQueue's ManagedObjectContext and it all works fine. Now I need a second table with Future-Activities and also a third table with Past-Activities. I need a ManagedObjectContext for each table as the sorting is done on the server side. How can I handle this and have persistent data. Is 'newChildManagedObjectContextWithConcurrencyType' what I need to use?
Keep a single store. Use a predicate to filter out the items you want.
If you can download all of the data (and you're happy to do that even though some of it may not be used by the user), and you can tag them for what they are used for then that is an option.
From a RestKit point of view, you can use metadata to tag the items during the mapping process so that you know how they should be used (and then filter on that). This requires that you add a new key to the item - but, if one item could be in all responses this will be problematic because the values would get overwritten.
To use metadata, simply add a new mapping like:
#"#metadata.URL": #"requestURL"
Where #metadata.URL is the URL used to make the request and requestURL is the property on your entity that you can use for filtering. The predicate will check for contains your types ("all_day" "start_time" "end_time").

Resources