0
votes

I've been researching this for a while and I think there are a number of solutions, but I'm not sure they are that good. It may be that I've missed something :-)

I have two tables. For each record in TableA there are multiple records in TableB. I.e. a one to many relationship. I've mapped it out in core data and generated the classes. So far so good.

My table view based UI needs to look like this:

Section 1
Cell 1: Table A: field1
Cell 2: Table A: field2
-----
Section 2
Cell 1: Table B: record 1: field1
Cell 2: Table B: record 2: field1
....

When I'm in my tableView:cellForRowAtIndexPath: it's easy to handle section 1 cells because they are different fields from the single Table A record. The section 2 cells are different. Each time tableView:cellForRowAtIndexPath: is called I need to get the correct Table B record from Table A's NSSet. And thats the problem.

NSSet doco indicates that it does not garrantee the order. Which means that if I want a specific record based on an index I have several possible techniques:

  • Add a sort descriptor to the core data query and use the fast enumeration to get to the record I want. I don't know if this will work because we are still working with an NSSet.
  • Sort the NSSet using a sort descriptor after getting the data to generate a NSArray and store that in a property before starting the table load.
  • I'm now thinking of a third option which is to write a decorator for an NSSet which acts like a NSArray and allows me to specify a sort field and automatically tracks changes to the NSSet. Tricky but might pay off in the long run.

neither of these answers seem that great. Is there a better way to do this?

2

2 Answers

1
votes

If you just want your objects, use the NSSet accessor.

If you want the object sorted, set up an NSFetchRequest and add the appropriate NSSortDescriptors.

Then, simply perform the fetch with executeFetchRequest:error:

Even better, Since this is specifically for a tableView, use NSFetchedResultsController to populate the table view. That's what it's there for.

0
votes

I've ended up with a NSArray being stored in the controller and sorting the NSSet records into it.