问题描述:

I have a Event entitiy in core data

with attributes eventName,eventDate,eventLocation.I am using SortDescriptors for key eventDate.I have a issue here i need to set location preferences for which i need to sort based on the location not as a key but value..For Ex-suppose i have location set to "Seattle" than all the events having location Seattle should display first.Do you have any idea how to do that with FetchControllers..Please read the question before answering

i DONOT want

[NSSortDescriptor sortDescriptorWithKey:@"eventLocation" ascending:YES];

but something like

[NSSortDescriptor sortDescriptorWithKey:@"eventLocation==Seattle" ascending:YES];

(which is wrong i know this is predicate format)

网友答案:

@sheetal, your situation is similar to the Phone app in iPhone, where contacts are displayed sorted by Last Name Ascending, and yet # must appear last (below Z). In other words, we want A B ... Z first and then #.

By the way, # stands for those Last Names which begin with other characters, such as @myHome, 133isACat, #puppy, etc. To get sections, we can create a new Transient attribute called lastNameInitial and feed that as SectionNameKeyPath. Assign lastNameInitial = @"#" if isLastNameNumeric (defined below) is YES. Else, assign the first letter of Last Name, such as A, B, etc., to lastNameInitial.

If we use a single sort descriptor in the sort descriptor array, namely one based on Last Name Ascending, then we would end up with # first, before A. To get around this, we can define a transient attribute called isLastNameNumeric (BOOL), which is 0 for "regular" last names (beginning with A B ... Z), and 1 for all others such as @myHome. Make a separate sort descriptor based on isLastNameNumeric Ascending and put it as the first sort descriptor in the array. Make the Last Name Ascending sort descriptor the second sort descriptor, which will do the subsorting according to last name.

To reiterate, the sort descriptor based on isLastNameNumeric Ascending is used just as an invisible helper.

A similar solution will work for you. However, if your eventLocation can change (is not always Seattle), then implementing this solution might be trickier.

If anybody has a better idea, either for showing A B ... Z first and then #, or for @sheetal's situation, I am all ears.

相关阅读:
Top