ios - 在搜索栏中的时间间隔后执行函数 - Objective-C

标签 ios objective-c uisearchbar

我想如果用户在搜索栏中输入文本后保持空闲 3 秒则执行一个函数。 我尝试使用以下代码:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {    
  ...    
    if ([searchText length] >= 3) { // If text length is greater than 3

      [NSRunLoop cancelPreviousPerformRequestsWithTarget:self 
               selector:@selector(searchBarSearchButtonClicked:) object:searchBar];

      [self performSelector:@selector(searchBarSearchButtonClicked:)
                               withObject:searchBar afterDelay:3.0]; 

   }

}

此代码的问题是,如果用户输入大于 3 的文本并按回车键,然后代码执行两次,有时它会因“无效计时器”而崩溃。。 p>

上面的代码应该做哪些修改?

最佳答案

我通过使用 NSTimer 找到了解决方案。以下是片段:

- (void) searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {

    [timer invalidate];
    timer = nil;    
    ...

    if ([searchText length] >= 3) { 

       timer = [NSTimer scheduledTimerWithTimeInterval: 3.0 target: self
             selector: @selector(SearchBarProxyCall) userInfo:nil repeats: NO];   
    }
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [timer invalidate];
    timer = nil;

    ...
}

-(void)SearchBarProxyCall { 
    [self searchBarSearchButtonClicked:searchbar];
}

关于ios - 在搜索栏中的时间间隔后执行函数 - Objective-C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27420483/

相关文章:

ios - 如何使用 Swift CoreData 删除表中的特定行

ios - Vscode React Native 在设备上运行

ios - 将方法从ViewController复制到AppDelegate-NULL

objective-c - 如何使用 NSCoding 加载 Objective C Singleton?

c - Objective C 版本的 explode()?

iphone - 如何让 iPhone 无限振动

ios - 使用 Xamarin 的 iOS 多路径 TCP

ios - 呈现 UISearchController 与状态栏重叠

ios - 如何知道搜索栏文本何时更改

ios - 在搜索栏上键入会破坏布局