ios - Does using blocks auto create new threads? -
just started doing work blocks... confusing. using block this:
-(void)tableview:(uitableview *)tableview didselectrowatindexpath:(nsindexpath *)indexpath { nsdictionary *mydictionary = [[mysingleton arraypeoplearoundme] objectatindex:indexpath.row]; nsmutablestring *mystring = [[nsmutablestring alloc] initwithstring:@"http://www.domain.com/4daction/pp_profiledetail/"]; [mystring appendstring:[mydictionary objectforkey:@"userid"]]; nsurlrequest *urlrequest = [nsurlrequest requestwithurl:[nsurl urlwithstring:[mystring stringbyaddingpercentescapesusingencoding: nsutf8stringencoding]] cachepolicy:nsurlrequestuseprotocolcachepolicy timeoutinterval:60.0]; nsoperationqueue *queue = [[nsoperationqueue alloc] init]; [nsurlconnection sendasynchronousrequest:urlrequest queue:queue completionhandler: ^( nsurlresponse *response, nsdata *data, nserror *error) { [[mysingleton dictionaryuserdetail] removeallobjects]; [[mysingleton arrayuserdetail] removeallobjects]; if ([data length] > 0 && error == nil) // no error , received data { nserror* error; nsdictionary *mydic = [nsjsonserialization jsonobjectwithdata:data options:kniloptions error:&error]; [mysingleton setdictionaryuserdetail:[mydic mutablecopy]]; nsarray *myarray = [mydic objectforkey:@"searchresults"]; [mysingleton setarrayuserdetail:[myarray mutablecopy]]; [self userdetailcomplete]; } else if ([data length] == 0 && error == nil) // no error , did not receive data { [self servererror]; } else if (error != nil) // error { [self servererror]; } }]; } once connection completed, called:
-(void)userdetailcomplete { viewprofile *vpvc = [[viewprofile alloc] init]; [vpvc setpassedinstructions:@"viewdetail"]; [[self navigationcontroller] pushviewcontroller:vpvc animated:yes]; } which caused error pop up: "tried obtain web lock thread other main thread or web thread. may result of calling uikit secondary thread." way got rid of error changing userdetailcomplete this:
-(void)userdetailcomplete { dispatch_async(dispatch_get_main_queue(), ^{ viewprofile *vpvc = [[viewprofile alloc] init]; [vpvc setpassedinstructions:@"viewdetail"]; [[self navigationcontroller] pushviewcontroller:vpvc animated:yes]; }); } my question: new thread started automatically every time block used? there other pitfalls should aware of when using blocks?
blocks not create threads. closures; contain runnable code can run @ future point.
this running on background thread because that's asked do:
nsoperationqueue *queue = [[nsoperationqueue alloc] init]; [nsurlconnection sendasynchronousrequest:urlrequest queue:queue ... you created new queue , asked nsurlconnection call on queue. if want called on main thread, pass [nsoperationqueue mainqueue]. that's waht want.
Comments
Post a Comment