How do I work with asynchronous spaghetti code?

I am writing a simple application using the iPhone iPhone SDK. The Facebook code is mostly asynchronous, I start the operation and get the response asynchronously in the delegate call:

- (void) doSomething { [FBSomething startOperationWithDelegate:self]; } - (void) fbOperationFinished: (FBSomething*) operation {โ€ฆ} 

Quite often, there are more instances of a given operation (say FBRequest ) that use the same callback. This means that I have to put a conditional clause in the callback handler to find out which of these operations has completed.

This leads to a messy, sort of โ€œasynchronous spygen code,โ€ because the code is full of conventions and it is almost impossible to see the logic of the program stream. Is there a better way to write such code? (Itโ€™s a shame that we donโ€™t have blocks on the iPhone.) I thought about introducing a simple state machine, but Im not sure if this will help.

+4
source share
4 answers

I am not familiar with the Facebook SDK, but you can simply create a subclass that implements the FBRequestDelegate protocol (if it is called that) for each specific task for which you need Facebook. So you say that 5 classes implement - fbOperationFinished: and not one class with 5 different execution paths, separated by if or switch es.

+10
source

There is no need to subclass Facebook API objects. I would highly recommend against this.

All facebook objects have a userInfo field that can be used to store information about requests. That way, you can store something there to identify the request or even a reference to an object to process the request.

It is much cleaner and more Cocoa-style frames.

+3
source

(It's a shame that we do not have blocks on the iPhone).

You can create a visual block using curly braces without a character. For example, animation blocks do not have a visual structure, but you can provide them as follows:

 // ...some code [UIView beginAnimations:@"selectionAnimation" context:nil];{ [UIView setAnimationDelegate:self]; [UIView setAnimationDuration:0.1]; [UIView setAnimationRepeatCount:1]; [UIView setAnimationRepeatAutoreverses:YES]; { //start properties to animate self.transform=CGAffineTransformScale(self.transform, 1.1, 1.1); } // end properties to animate [UIView commitAnimations]; } // more code... 

This is not a logical block, but it is better than nothing. You can also use them to collapse code. I use them to hide assertions or debugging code.

+1
source

I would put these queries in NSOperationQueue, so each one is different and also throttles how many you have active at the same time.

You just need to wrap the requests in an NSOperation object (which the Facebook API may already have?)

0
source

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


All Articles