开发者

How to simulate a left-join with coredata on iphone

i'm working with 2 entities in coredata :

  • worker
  • office

A worker work in one (and only one) office.

An office is occupied by several workers.

Now I would like populate a TableView with workers, grouped by office. This represent the table view :

Section 1 : Office 1

.........开发者_JAVA技巧.Worker 1

..........Worker 2

..........Worker 3

Section 2 : Office 2 (empty)

Section 3 : Office 3

..........Worker 4

..........Worker 5

In SQL I could use this query :

SELECT *  
FROM office 
LEFT JOIN worker ON office.officeId = worker.officeId  
order by office.name, worker.name

Now working with core data, I'm facing some problems :

  • If I fetch office, I can access to workers (from relationship) as a Set, but this is not adapted to work with table view (for sorting and manipulating)
  • If I fetch worker and access the office via the relationship, empty offices are not fetched.

How can I fetch data like this with coredata ?

Thanks


I would fetch the offices, then simply sort the workers set (alphabetically, according to a rank attribute, etc) for display in the table. It'll probably make sense to make a method on your Office entity class to returned a sorted array for workers, e.g.:

@implementation Office

- (NSArray *)sortedWorkers
{
    return [self.workers sortedArrayUsingDescriptors:
            [NSArray arrayWithObjects:
             [NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES],
             [NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES],
             nil]];
}


Fetch your workers and use the offices for the the sections as you have already done. Empty offices should not be shown in a UITableView as it goes against the HIG.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜