Search code examples
iosdatabasecore-dataentityrelationships

Load up entity from db rather than pulling data directly from db


I created an iOS app that allowed me to enter data into database and then display in tableview (using NSFetchedResultsController & tableView cellForRowAtIndexPath). This worked. Now, I added 3 one-to-many relationships and another entity and I need to load up the entity (on the one side of the one-to-many) from the db instead of pulling it directly from the db so that the data can be used in the relationships. Do I still use NSFetchedResultsController?

relationshipEntity2 is the one-to-many relationship between Entity1 & Entity2. The many point to Entity2

I know I'm supposed to use:

Entity2 *entity2 = [[self.entity1.relationshipEntity2 allObjects] 
   objectAtIndex:indexPath.row];

I am new to iOS development and even newer to Core Data but I must learn it. Any bit of help or pointing to a book or tutorial I haven't come across yet would be greatly appreciated. I haven't had much luck finding anything that does what I'm supposed to be doing.

Thanks and have a great week!

-------added for more description on project-------
I'm given the task of having a View Controller with a 3-part segmented button. There is also an add UIButton that pops up a view (bringing subview to the front, not a popover segue) with a UITextField for input to add to the table view on the view controller. There are 2 entities and three 1-to-many relationships. There is 1 relationship for each button on the segmented button. If the user, has the first part of the segmented button selected, adding a value to the popup textbox, should only add it to the table view seen when the first segmented button is selected. I have the CoreDataGeneratedAccessors created. I had this project saving data to database and fetching data to present in the table view but that was before the segmented part was added. Now I have to figure out out to separate the data into "collections" and then show all of say the first collection when the first segment of the segmented button is chosen. I'm just learning and just figured it out without the segmented part and now it's changed on me. I've worked with relational databases but in iOS it seems like it's new again.


Solution

  • Your question is by no means clear. You are not describing any problem, nor do you explain intelligibly what you want to accomplish.

    Trying to infer your meaning: yes, you would continue to use your fetchedResultsController. This controller gives you the right object for each indexPath. When building your cell contents, you can easily get to the relationship entities with entity.relationship.

    The code above will not work because entity.relationship returns an NSSet which is an unordered group of objects. (The additional allObjects does nothing and is redundant.) Therefore, objectAtIndex will not work (this only works for NSArray objects).

    Hope this helps.