Determine the end of execution. SelectorInBackground: withObject:

I have an asynchronous server request in my iOS application:

[self performSelectorInBackground:@selector(doSomething) withObject:nil]; 

How can I determine the end of this operation?

+4
source share
4 answers

Put a call at the end of the doSomething method ?!

 - (void)doSomething { // Thread starts here // Do something // Thread ends here [self performSelectorOnMainThread:@selector(doSomethingDone) withObject:nil waitUntilDone:NO]; } 
+15
source

If you just want to know when he finished (and don’t want to transfer a lot of data back - at what point I would recommend a delegate), you could just send a notification to the notification center.

 [[NSNotificationCenter defaultCenter] postNotificationName:kYourFinishedNotificationName object:nil]; 

in your view the viewDidLoad controllers add method:

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(yourNotificationListenerMethod:) name:kYourFinishedNotificationName object:nil]; 

and in dealloc add:

 [[NSNotificationCenter defaultCenter] removeObserver:self]; 
+1
source

You might want your doSomething to switch after it completes itself. What happens in performSelectorInBackground is internal to the API, and if you want more control, you can use performSelector:onThread:withObject:waitUntilDone: and periodically check isFinished on the passing thread. I'm sure you are more concerned that doSomething is ending than the actual thread, although so just send it back from there.

0
source

I have a general background handler that I created that solves this problem. Only the first method is publicly available, so it can be used everywhere. Please note that all parameters are required.

 +(void) Run: (SEL)sel inBackground: (id)target withState: (id)state withCompletion: (void(^)(id state))completionHandler // public { [(id)self performSelectorInBackground: @selector(RunSelector:) withObject: @[target, NSStringFromSelector(sel), state, completionHandler]]; } +(void) RunSelector: (NSArray*)args { id target = [args objectAtIndex: 0]; SEL sel = NSSelectorFromString([args objectAtIndex: 1]); id state = [args objectAtIndex: 2]; void (^completionHandler)(id state) = [args objectAtIndex: 3]; [target performSelector: sel withObject: state]; [(id)self performSelectorOnMainThread: @selector(RunCompletion:) withObject: @[completionHandler, state] waitUntilDone: true]; } +(void) RunCompletion: (NSArray*)args { void (^completionHandler)(id state) = [args objectAtIndex: 0]; id state = [args objectAtIndex: 1]; completionHandler(state); } 

Here is an example of how he called:

 NSMutableDictionary* dic = [[NSMutableDictionary alloc] init]; __block BOOL done = false; [Utility Run: @selector(RunSomething:) inBackground: self withState: dic withCompletion:^(id state) { done = true; }]; 
0
source

Source: https://habr.com/ru/post/1344935/


All Articles