objective c - How to cancel a completion handler in iOS -


i want array of nearby locations using mapkit framework. when user types in textfield call following function.

- (void)searchforlocations:(nsstring *)string {     [nsobject cancelpreviousperformrequestswithtarget:self selector:@selector(search:) object:nil];     [self performselectorinbackground:@selector(search:) withobject:string]; }  - (void)search :(nsstring *)string {     mklocalsearchrequest *request = [[mklocalsearchrequest alloc] init];     request.naturallanguagequery = string;     mkcoordinateregion region;     mkcoordinatespan span;     span.latitudedelta = 0.05;     span.longitudedelta = 0.05;      region.span = span;     region.center = newlocation.coordinate;      request.region = region;      mklocalsearch *search = [[mklocalsearch alloc]initwithrequest:request];      [search startwithcompletionhandler:^(mklocalsearchresponse                                          *response, nserror *error) {         if (response.mapitems.count == 0)         {             nslog(@"no matches");         }         else         {              nslog(@"name = %@", item.name);             nslog(@"phone = %@", item.phonenumber);         }     }]; } 

as can see want cancel previous search if new input text coming. previous search not cancelled. how can cancel previous search?

thanks in advance.

there cancel method on mklocalsearch. have tried one?

edit: ah, sorry, being stupid. need keep reference old search in way in order cancel it. put in property can clear (i.e. set nil) when search finished. whenever call search function, cancel previous search function (no "if" needed, nil swallows all), create new 1

@property (nonatiomic, strong) mklocalsearch *previoussearch;  - (void)search :(nsstring *)string {     [self.previoussearch cancel];     mklocalsearchrequest *request = [[mklocalsearchrequest alloc] init];     request.naturallanguagequery = string;     mkcoordinateregion region;     mkcoordinatespan span;     span.latitudedelta = 0.05;     span.longitudedelta = 0.05;      region.span = span;     region.center = newlocation.coordinate;      request.region = region;      mklocalsearch *search = [[mklocalsearch alloc]initwithrequest:request];      [search startwithcompletionhandler:^(mklocalsearchresponse                                      *response, nserror *error) {         self.previoussearch = nil;         if (response.mapitems.count == 0)         {             nslog(@"no matches");         }         else         {              nslog(@"name = %@", item.name);             nslog(@"phone = %@", item.phonenumber);         }     }];      self.previoussearch = search; } 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -