hrnt
hrnt

Reputation: 10142

Creating Core Data relationships quickly from relational data (iOS)

I am using Core Data to store data from the server that is sent in a "relational" form.

For example, the data I get from the server looks something like this (the actual format is somewhat different, but similar enough)

Users: [{PK: 1, Name: 'A B'}, {PK: 2, Name: 'C D'}, {PK: 3, Name: 'E F'}]
Posts: [{PK: 1, UserPK: 1, Content: '...'}, {PK: 2, UserPK: 3, Content: '...'}]

My Core Data model has an relationship set between Users and Posts and it works like it should. However, my problem is creating these objects and their relationships as fast as possible (without using ridiculous amounts of RAM) when I receive a new dataset from the server.

The problem is associating the posts with the users. The "normal" way to do it is to basically write post.user = user; However, this requires that I have the user loaded from the disk.

My current plan is to load all users, fault them and create a NSDictionary that maps the PK's to the actual objects. That way I can quickly find out the user I need to associate with the post. However, this solution seems a bit complex for something that should essentially be a rather trivial operation.

Upvotes: 2

Views: 145

Answers (2)

Marcus S. Zarra
Marcus S. Zarra

Reputation: 46718

Your solution of keeping the users in memory in a NSDictionary is sound. They should not take very much memory at all as long as you leave them in a faulted state. A faulted MO is tiny.

Upvotes: 2

Toastor
Toastor

Reputation: 8990

I had a very similar situation and ended up not importing the data into core data at all, because the repeated imports for hundreds of data objects plus relationships where just too slow. It turned out that the parser I wrote for that format was sufficiently fast to read data in realtime (while scrolling tableviews etc.) though, so I basically just saved the raw data to disk.

The parser needed to be expanded, it now outputs data objects similar to managed objects, which allows to query the raw data using KVC.

I kept using Core Data for saving user edits and introduced a data manager class to bring both data sources together.

Not quite what you asked for, I guess, but maybe it helps...

Upvotes: 0

Related Questions