I have UIViewController having a UISearchBar and UITableView. The table view is used to show recent searches.
I am using NSUserDefaults to save the search texts.
Here is what I’m doing:
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
DLog(@"Search")
NSString *searchText = [self.searchBar text];
[self.recentSearchesDict setObject:searchText forKey:searchText];
self.recentSearchesStrings = [[self.recentSearchesDict allValues] mutableCopy];
[self saveRecentSearches];
[self.recentSearchList reloadData];
}
I save the text object in NSMutableDictionary with the same text to as the key to avoid duplicate entries in the table view.
and:
- (void)saveRecentSearches
{
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
if (self.recentSearchesDict) {
[currentDefaults setValue:self.recentSearchesDict forKey:@"recentSearchesArray"];
}
}
saves the NSMutableDictionary to NSUserDefaults.
In viewDidLoad I’m calling this:
- (void)loadRecentSearches
{
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
self.recentSearchesDict = [[currentDefaults objectForKey:@"recentSearchesArray"] mutableCopy];
if (!self.recentSearchesDict) {
self.recentSearchesStrings = [[NSMutableArray alloc] init];
self.recentSearchesDict = [NSMutableDictionary dictionary];
return;
}
self.recentSearchesStrings = [[self.recentSearchesDict allValues] mutableCopy];
}
for populating the table view I’m using the NSMutableArray object recentSearchesStrings.
The problem is that when the array takes all values from the dictionary, they are not in order of most recent.
I want the latest to be displayed on top of the list.
Any help? Is there any other better approach to achieve the desired task?
You should not use a dictionary to save the recent searches if you want to preserve the order, because there is no defined order on key/value pairs in a dictionary.
You should store the
recentSearchesStringsarray itself in the user defaults. To add an item to the array while removing duplicates you can do