iOS - 延迟后的Web服务请求

Rav*_*avi 4 iphone delayed-execution ipad ios performselector

我有一个搜索栏,其中包含一些建议UITableView,这些建议会在用户输入时填充(使用JSON服务).这些服务调用需要在延迟500ms的非打字后进行.如果用户开始输入500ms的这段时间,则需要取消队列中的当前呼叫,并且应用程序必须等待另外500ms的非活动才能再次afterDelay呼叫.我知道我必须performSelector:withObject:afterDelay在整个情况下使用,但我无法适应条件.我尝试使用一堆bool但它只是变脏......任何帮助?

Jac*_*ies 7

我会用NSTimer而不是performSelector:withObject:afterDelay:.检测文本何时发生变化UISearchBar并重置计时器.

-(void)viewDidLoad {

    search.delegate = self;

}

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

    [timer invalidate];

    timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(callTheService) userInfo:nil repeats:NO];

}
Run Code Online (Sandbox Code Playgroud)


Car*_*zey 6

假设您正在检测UITextFieldDelegate方法中的输入,那么这个怎么样:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(sendNetworkRequest) object:nil];
    [self performSelector:@selector(sendNetworkRequest) withObject:nil afterDelay:0.5];
    return YES;
}

- (void)sendNetworkRequest
{
    // Here immediately send the request
}
Run Code Online (Sandbox Code Playgroud)

我喜欢这个appraoch这样的问题,因为它意味着我不必使用NSTimer或跟踪任何状态,我是否在等待是否输入更多文本.希望这可以帮助!如果您有任何疑问,请告诉我.

编辑:看到你正在使用搜索栏.原理是一样的,只需将取消/执行配对放在适当的UISearchBarDelegate方法中.