开发者

NSSortDescriptor and to-many relationships

开发者 https://www.devze.com 2023-04-11 01:34 出处:网络
I\'m working with an NSFetchedResultsController to show data in a UITableView. I have a to many relationship which looks something like this:

I'm working with an NSFetchedResultsController to show data in a UITableView. I have a to many relationship which looks something like this:

Article ---->> Tag

One article has many tags.

I'd like to order them so that all tags that have the title "Banana" come before those that have the tag "Orange" which in turn are before those tagged "Apple" etc. The title is an attribute on the tag.

I was considering using an NSSortDescriptor. I've implemented a method called "position" in my Tag NSManagedObject subclass. This method returns an NSInteger which describes the order of the tags.

The issue is that NSSortDescriptor does not support to-many relationships. (The console reads: "to-many key not allowed here".) Here's what I tried:

    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"tags.tagText" ascending:YES comparator:^NSCompariso开发者_开发技巧nResult(id obj1, id obj2) {

    if ([obj1 position] > [obj2 position]) { 
         return (NSComparisonResult)NSOrderedDescending;
        }
    if ([obj1 position] < [obj2 position]) {
        return (NSComparisonResult)NSOrderedAscending;
         }
    return (NSComparisonResult)NSOrderedSame;
}]; 

Any idea what the answer is? How can I do a sort based on an arbitrary value of a property of another entity which is linked via a to-many relationship?

EDIT:

I'm now wondering if I can use a method in my Article class to help with the sorting. I would do something like this:

 - (NSInteger)position{

NSInteger aPosition = 100;

for (Tag *aTag in self.tags) {
    if (position > [aTag position]) {
        aPosition = [aTag position];
    }
}

return aPosition;
}

Is there a way to have my NSSortDescriptor call this method?


Ok, so the Tag has a title attribute and you want to display a tableview full of articles that are broken into sections where the section is the title from the tag?

Assuming that is correct the short answer is you can't. The sort doesn't make sense because an Article can and will be in more than one position in the sort. If an article has the tag Apple and Orange, where should it be placed?

0

精彩评论

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

关注公众号