我有一个带有4个范围按钮的UISearchBar。下次用户在目标C中选择另一个范围按钮时,我需要存储按下的范围按钮。请问有什么想法吗?
已解决: 这是其他人的解决方案
static NSString *yourKey = @"savedScopeSelection";
viewDidLoad
- (void)viewDidLoad
{
NSInteger newIndex = [[NSUserDefaults standardUserDefaults] integerForKey:yourKey];
[self.searchDisplayController.searchBar setSelectedScopeButtonIndex:newIndex];
}
UISearchBar范围
- (void)searchForText:(NSString *)searchText scope:(UYLWorldFactsSearchScope)scopeOption
{
if (self.managedObjectContext)
{
NSString *predicateFormat = @"%K contains[cd] %@";
NSString *searchAttribute = @"option0";
[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:yourKey];
if (scopeOption == searchScopeOption1)
{
searchAttribute = @"option1";
[[NSUserDefaults standardUserDefaults] setInteger:1 forKey:yourKey];
}
if (scopeOption == searchScopeOption2)
{
searchAttribute = @"option2";
[[NSUserDefaults standardUserDefaults] setInteger:2 forKey:yourKey];
}
if (scopeOption == searchScopeOption3)
{
searchAttribute = @"option3";
[[NSUserDefaults standardUserDefaults] setInteger:3 forKey:yourKey];
}
if (scopeOption == searchScopeOption4)
{
searchAttribute = @"option4";
[[NSUserDefaults standardUserDefaults] setInteger:4 forKey:yourKey];
}
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateFormat, searchAttribute, searchText];
[self.searchFetchRequest setPredicate:predicate];
NSError *error = nil;
self.filteredList = [self.managedObjectContext executeFetchRequest:self.searchFetchRequest error:&error];
if (error)
{
NSLog(@"searchFetchRequest failed: %@",[error localizedDescription]);
}
}
}
答案 0 :(得分:1)
这似乎是使用NSUserDefaults的好时机。
在某处设置静态密钥
static NSString *yourKey = @"savedScopeSelection";
进行选择时,存储所选索引的值:
[[NSUserDefaults standardUserDefaults] setInteger:newIndexValue forKey:yourKey];
初始化搜索栏时,请查找默认值以获取存储的索引:
NSInteger *newIndex = [[NSUserDefaults standardUserDefaults] integerForKey:yourKey];
我建议您将每个范围按钮都用整数表示。您可以使用如下枚举:
enum ScopeButtonIndex: Int {
case thisScope = 1
case thatScope = 2
case otherScope = 3
case fourthScope = 4
}
我想专门为其提供索引,因为我将其存储在userDefaults中,并且我不想在将来的某些版本中通过添加另一个值来意外更改索引值