Delaying, cancelling or replacing a ASIFormDataRequest in a NSOperationQueue (for a searchbox)
I'm successfully making a ASIFormDataRequest using the below code.
//get groups
if (![self queue]) {
[self setQueue:[[[NSOperationQueue alloc] init] autorelease]];
}
//make the url by appending the URL from the Constant class to the jsp name
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", URL, @"connectors/searchGroupsServlet.jsp"]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addRequestHeader:@"User-Agent" value:USER_AGENT];
[request addPostValue:[login username] forKey:@"username"];
[request addPostValue:[login password] forKey:@"password"];
[request addPostValue:[searchText lowercaseString] forKey:@"query"];
[request addPostValue:GROUP_FILTER_LIMIT forKey:@"limit"];
[request setDelegate:self];
[reques开发者_开发问答t setDidFinishSelector:@selector(requestDone:)];
[request setDidFailSelector:@selector(requestWentWrong:)];
This request is currently made on every key press a user makes in a searchbox (The text typed is sent off in the request as the search string). However, rather than sending the request on every key press, I want to delay the request by a second to allow users to type further characters into the searchbox before the request is sent.
I've successfully made a thread that waits a second as users continue to type (although admittedly Im not convinced this is the best way to do it yet, but it works for now)...
this
[self performSelectorInBackground:@selector(wait:) withObject:request];
calls this
-(void)wait:(NSString *)request
{
[NSThread sleepForTimeInterval:1.00];
[[self queue] addOperation:request]; //queue is an NSOperationQueue
}
but, if a user continues to type, I haven't managed to work out how to cancel the request or not put the request in the queue, or empty the queue and replace it with the new request.
Finally, obviously I could force users to wait until they have pressed the 'search' button on the pop-up keyboard, but I was hoping to provide search results without that.
Thanks
The answer was to create an NSTimer, and invalidate it whenever a new key press had been made. Then start it again.
[timer invalidate];
You can try this to cancel
+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget selector:(SEL)aSelector object:(id)anArgument
精彩评论