Saving to Core Data with NSMutableArray - iphone

Been having a bit of a headache with this one and was wondering if someone could offer some advice!
Im implementing persistent storage with Core Data.
I have two Entities Car and Driver. A car can have many drivers.
In one view i am collecting the drivers and storing them to a NSMutableArray
This array is getting passed to another view and at some point i will be saving it against a Car
What i would like to do is save each driver from the array in a seperate row in the table of drivers (Just their name (NSString) which will be assigned to a Car.
I can create an entry in the database for Car but am struggling with saving each driver in a seperate row in the driver table assigned to that car.
Any suggestions or pointers in the right direction would be greatly appreciated!
Cheers :)

It would be difficult to encapsulate a complete solution to your answer, as your question is fairly broad without seeing your code.
Try to walk through Apple's excellent Books and Recipes sample applications, which cover the Core Data concepts you'll need to progress with your own project.

You mention that you have both Car and Driver entities, yet it sounds like you're trying to save your driver names directly as attributes of a car. Why are you just saving their NSString *name to the car?
Instead of doing that, you should simply update the relationships between your car and its drivers. If you implement your entities as custom classes (and I highly recommend it - see this ADC guide), then when you want to update who drives what car, you can simply say: [car addDriversObject:driver] or [car removeDriversObject:driver].
Like Alex said, you may want to ensure you have a firm grasp on Core Data before heading out on your own too far.

i'm not a pro in using core data, but you can try to get data from your array using NSKeyArchiver and save returned NSData object to your database. it works fine with sqllite databases.

Related

Would containing NSData in a different Core Data entity make retrieval of the original entity faster?

So here's my example. I have an entity called Photo. It has the attributes of 'width' and 'height', for easy retrieval, and a NSDate of when it was taken. It also has an NSData of the photo itself. If i moved this NSData to an attribute with a one-to-one relationship to Photo, would it increase saving speed if I changed another attribute in Photo, or fetching speed if i fetched another attribute in Photo?
I would suggest making it a external data reference.
There is an example of this exact thing in one of the WWDC talks https://developer.apple.com/videos/wwdc/2012/ where they go through the speed of the different types of schema and their fetch times. The talk is called Core Data Best Practices and is a long demo around the 35 min. mark where they talk about external data refs. The whole talk is very very good but that is the relevant bit.
Your idea is correct, they create a 1-1 separate entity with a external data ref. and it speeds things up a lot.
Here is a link to the slides:
http://adcdownload.apple.com//wwdc_2012/wwdc_2012_session_pdfs/session_214__core_data_best_practices.pdf

Need help using core data to hold my parsed data

I am at a real loss.. For the past two weeks I have been working on fine tuning the way data is parsed, displayed and held in my app.
I have two view controllers, the first has four tables that when selected load a uitableview full of data that is parsed from an xml file. each xml file is different but have key fields that relate to each other. I need to speed up the way I display this data in the uitableview as when I do my second search when I check my ManufactureID against every single modle avalible to all manufactures.. it take a considrible amount of time to load.
I would like to do this behind the scenes before the view is even about to load and I have heard the best way to achieve this will be to use core data.. but I am not sure how to get this to work with the way I am doing things now.
If you have any examples, suggestions or anything that might help me I could seriously use someones input right about now as I am just abit stuck. For instance how do I get the data that are in my .xml files into the coredata? how to I create the relation ship ID's? etc.
First off, is there any reason to keep the information in XML files? Everything will be a lot easier (and faster!) if you just move it all to a CoreData datastore from the start instead of parsing/preloading everything to an in-memory store at launch (or whatever).
As to how to model your relationships, you could always set your CoreData model to exactly match your XML data. So, say, one Entity per file and one Attribute per record in said file. There's no reason you have to use CoreData Relationships to model the relationships in your XML. If you have IDs in the files already, just make an Attribute called xmlId or something and fetch based on that just like you were doing a SQL query. You'd miss out on a lot of automatic ORM-ness of CoreData, but if you've been dealing with XML this whole time, I doubt you'll notice.
If you really want to set up the relationships between your CoreData-managed objects, you'll have to somehow match up objects by their IDs in the XML either by importing the IDs into CoreData and then doing the math, or by somehow taking care of this when you parse. Hard to give any specific advice here without knowing more about how your data are modeled.
There's some sample code that does half of what you want (it reads XML into a in-memory CoreData store, but doesn't model any relationships). Check out TopSongs (http://developer.apple.com/library/ios/#samplecode/TopSongs)

Syncing up Core Data with a NSMutableArray

I know this is probably a pretty basic question, but I'm working with Core Data and a UITableView. I import all the data from Core Data to various mutable arrays. When a user rearranges the items in the table, it's easy enough to swap the items in the mutable arrays I obtained from core data earlier, but is there an easy way to sync the new mutable array with the existing core data? Any help is appreciated!
I think your question is actually how to persist the order of the data in your table view rows in Core Data.
The answer is you have to introduce a new integer / NSNumber attribute to keep track. I have done this in a simple app managing a to-do list.
Use a NSFetchedResultsController. It greatly simplifies using a table view and Core Data together. No need worrying about intermediary arrays.
Lion added support for ordered to-many relationships, which is much easier than storing the indices within the entities. If you're targeting Lion you can mark the relationship Ordered and access it using a new class NSOrderedSet, which will persist its order, like an array.

Sample code illustrating MVC architecture in iOS

I'm trying to get the hang of MVC architecture. Say I have a plist in which there are a list of persons and each person has a few attributes like name, address and photograph. Suppose
I want to display these details in a table view. The cell title would be the name, description would be the address and the image towards the left would be the photograph of the person.
One approach I could take is to load the plist in an array-of-dictionaries in my viewDidLoad: and then display them.
However, I want to adopt an Object Oriented method by creating 'Person' class. How do I go about doing the same in this case? I believe I could start by creating a 'Person' class with three attributes:Name, Address, Photograph. What next? I would need many instances of this 'Person' class right? How would I 'load' each instance with a corresponding Person entry from the plist? Should I create another class that does this 'loading'? Do people use Singleton class to achieve his?
Could someone share some sample sample code to illustrate this? Or maybe guide me to blogs/resources that talk about this?
Hmmm, I think you are over thinking this a bit. I would just create a class that would handle my person, in this case your 'Person' class.
I would simply store each person using Core Data. Then, when it's time to display them, I would just make a fetch request and store all person managed objects into an NSMutableArray (which simply handles arrays of objects). Then you can simply use the index value to display the numerous persons in your array in a tableView.
In summary I would:
1. For every person, create instance of Person.
2. Verify if person exists in my Core Data Person Entity.
3. If not, then insert into Core Data (the object will become an
NSManagedObject).
4. For displaying, simply do a fetch request to pull all persons in your
entity. Here I prefer to store the
results into an NSMutableArray, but
that is completely up to you. Make
sure you release your fetch request
after the results are store in the
array.
5. Reference them to your table view using the index value for each
person NSManagedObject in the array.
For something that doesn't involve storing simply:
1. Create instance of Person for every entry.
2. Add Person object to array.
3. Reference each Person to table view using index value.
In the end the approach that you take will be dictated by what you want to do with the information.
As for reading the plist, I would opt for reading an XML for which all you need is an XML Parser class (there are several options for parsers). Since I don't do anything but parse the XML, I use NSXMLParser, but that choice is also up to you. Just create an NSXMLParser class (make sure that the different actions for when the parser finds a given element are in play inside that parser). So yes, you would need to make additions to the NSXMLParser for handling each element. It's really easier than it sounds.
Also, by storing in Core Data, you can always fetch the info without you using a Singleton.
I believe you are not looking for a design solution to the above mentioned question. If that is the case #A Salcedo 's version looks fine.
if you are looking for general guide lines for MVC and modeling , Martin Fowler's site offers some of the best (agile) design/modeling guidelines.
http://www.martinfowler.com/eaaDev/uiArchs.html (on MVC) and
http://martinfowler.com/design.html (many interesting design related posts).
Happy reading.

Modelling entity types using Core Data

I'm working on my first app using Core Data and I need to assign a type (with an associated name attribute) to a couple of entities.
Below is my object model so far.
The room and item types will be updated from time to time over the network.
Is this the best way to implement this using Core Data? Thanks :)
Edit: To try to explain better: for example, rooms may be Bedrooms, Kitchens etc. Items can be Aircon, Security Camera etc. The only difference between the different room and item types is the name text. The list of valid name texts will be updated so I don't want to hard code it in the app. Also, the user can create multiple rooms and items of the same type, which is why they are numbered (roomNumber,itemNumber)
improved Core Data Model Image http://img42.imageshack.us/img42/8458/picture6c.png
Nick, try and avoid the temptation of thinking of Core Data as a database. Design your model from the point of view looking at using the objects in your code.
i.e. your relationship properties are collections (or singluars) of the related thing.. you should rename the relationship JobLocation.JobLocationToRoom as just JobLocation.rooms
And yes, using Core Data will be quite straight forward, but it's hard to give you a definitive answer with such a vague question.
Perhaps my question wasn't clear, but I found the answer in the Apple iPhoneCoreDataRecipes demo code
The relationship I wanted to model is similar to Recipe -> RecipeType.
In addition to the other answers, you don't need to model separate ID attributes. Core Data managed objects automatically have managed object IDs that are handled for you entirely behind-the-scenes by the framework.