我想如果用户在搜索栏中输入文本后保持空闲 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/