objective c - How to kill NSThread while clicking on new tab iOS? -


i building app has 4 tab (tabbar controller), , each tab call function (updatearray) after 2s. want when click on other tab, updatearray() function kill. problem when on tab, updatearray() call after 2s, when click on other tab, function still call.

this updatearray()

-(void)updatearray{     while (loop)    {        [nsthread sleepfortimeinterval:2.0];        [filecompletedarray removeallobjects];        [temp removeallobjects];        [usernamearray removeallobjects];          nsurl *url1 = [nsurl urlwithstring:@"server"];          afhttpclient *httpclient = [[afhttpclient alloc] initwithbaseurl: url1] ;            nsmutableurlrequest *afrequest = [httpclient requestwithmethod:@"post" path:nil parameters:params1] ;          afhttprequestoperation *operation = [[afhttprequestoperation alloc] initwithrequest:afrequest];          [operation  setcompletionblockwithsuccess:^(afhttprequestoperation *operation, id responseobject) {             nslog(@"success");             nsstring * parsexmlinput = [[nsstring alloc] initwithdata:responseobject encoding:nsutf8stringencoding];             nslog(@"response in loop completeview: %@", parsexmlinput); //000400010001            // dispatch_async(dispatch_get_main_queue(), ^{                 [self parsexmlfile:parsexmlinput];              nslog(@"file completed array: %@", filecompletedarray);             nslog(@"file temp out array: %@", temp);             nslog(@"file completed count: %lu",(unsigned long)[ filecompletedarray count]);             nslog(@"file temp out count: %lu", (unsigned long)[temp count]);              if([filecompletedarray count] != [temp count])             {                 temp = [filecompletedarray mutablecopy];                  nslog(@"file temp 1 array: %@", temp);                 [_tableview reloaddata];                 nslog(@"file temp 2 array: %@", temp);              }             [alert dismisswithclickedbuttonindex:0 animated:yes];       //});         }       failure:^(afhttprequestoperation *operation, nserror *error) {                                               nslog(@"error: %@", error);                                            }          ];         [httpclient enqueuehttprequestoperation:operation];    } } 

and in viewwillappear()

-(void) viewwillappear:(bool)animated {     [super viewwillappear:animated];     loop = yes;      temp = [filecompletedarray mutablecopy];     [self performselectorinbackground:@selector(updatearray)  withobject:nil ];  } 

in function, used [nsthread sleepfortimeinterval:2.0];, don't know how kill it. have suggestions ? in advance

you shouldn't use sleepfortimeinterval, should use performselector:withobject:afterdelay: (and cancelperformselectorswithtarget:) or dispatch_after.

as is, can add bool attribute used decide if thread should continue after sleep or whether should exit (return).


Comments