Using a button to determine to sort ascending or descending in iPhone
What is the best way to do this? I currently just sort ascending by using a sortDescriptor like so:
NSSortDescriptor *Descriptor = [[[NSSortDescriptor alloc] initWithKey:@"Name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)] autorelease];
Now if I have a checkButton that is used to determine if the user wants to sort by descending or开发者_开发知识库 ascending, what is the best way to handle this? Do I check for the checkButton's state before creating the sortDescriptor? And then if the user hits the checkButton again (create another sortDescriptor of the opposite type (ascending or descending), then run the method to show the data in the new sorted mode? Thanks.
I'd hook the button up to a function that creates your sort descriptor and fetches your results. This results in a fetch being made each time the state is altered.
Pick a default, use this as the default sort type without any user-interaction, and then users can change their preference with the button.
I hope you find this handy!
@interface MyController... {
BOOL _sortAscending;
}
@implementation MyController
(IBAction)swapSort {
_sortAscending = !_sortAscending;
NSSortDescriptor *Descriptor = [[[NSSortDescriptor alloc] initWithKey:@"Name" ascending:_sortAscending selector:@selector(localizedCaseInsensitiveCompare:)] autorelease];
//whatever else you need to do
}
Essentially, yes.
I'm curious why you're asking this question, since you basically answer it yourself (in the form of a series of "Should I?" questions).
What you describe is a fairly common pattern. The button doesn't really determine the sort order, though. Your app maintains a Configuration which includes the sort order and maybe some other things. The Configuration always includes a sort order, the button allows you to change it. Anything that uses the Configuration should be notified when it changes, so that it can update the views that need updating.
There are lots of different ways to do this, and there's no One Right Way for all situations. Perhaps the button is responsible for telling the table that it updated the sort order. Or perhaps the table is responsible for observing changes to the configuration. Either way works.
精彩评论