I am writing a simple application using the Facebook iPhone SDK. The Facebook code is mostly asynchronous, I start an operation and receive the response asynchronously in a 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 into the callback handler to know which of these operations finished.
This leads to messy, a kind of “asynchronous spaghetti code” monster because the code is full of conditionals and it’s almost impossible to see the program flow logic. Is there a better way to write such code? (It’s a shame we don’t have blocks on iPhone.) I thought about introducing a simple state machine, but I’m not sure it will help.
I’m not familiar with the Facebook SDK, but you could just create a subclass that implements the
FBRequestDelegateprotocol (if it’s called like that) for every specific task you need Facebook for. This way, you have say 5 classes implementing- fbOperationFinished:rather than one class with 5 different execution paths separated byifs orswitches.