views:

209

answers:

2

I have the following scenario:

Class_A
  - method_U
  - method_V
  - method_X
  - method_Y

Class_B
  - method_M
  - method_N

HttpClass
  - startRequest
  - didReceiveResponse // is a callback

Now I want to realize these three flows (actually there are many more, but these are enough to demonstrate my question):

Class_A :: method_X -> HttpClass :: startRequest:params -> ... wait, wait, wait ... -> HttpClass :: didReceiveResponse -> Class_A :: method_Y:result

and:

Class_A :: method_U -> HttpClass :: startRequest:params -> ... wait, wait, wait ... -> HttpClass :: didReceiveResponse -> Class_A :: method_V:result

and the last one:

Class_B :: method_M -> HttpClass :: startRequest:params -> ... wait, wait, wait ... -> HttpClass :: didReceiveResponse -> Class_B :: method_N:result

Please note, that the methods in Class_A and Class_B have different names and functionality, they just make us of the same HttpClass.

My solution now would be to pass a C function pointer to startRequest, store it in the HttpClass and when didReceiveResponse gets called I invoke the function pointer and pass the result (which will always be a JSON Dictionary).

Now I'm wondering if there can be any problems using plain C or if there are better solutions doing it in a more Objective-C way. Any ideas?

+4  A: 

You can use selectors instead of function pointers. Basically you setup for 1st scenario would be:

// declare startRequestWithDelegate method
- startRequestWithDelegate:(id)delegate selector:(SEL)selector;

// call it in Class_A object:
[HTTPObject startRequestWithDelegate:self selector:@selector(method_Y:);

// call callback method when request finished:
if ([delegate respondsToSelector:savedSelector])
   [delegate performSelector:savedSelector withObject:result];

Other scenarios will differ in calling startRequestWithDelegate method.

Vladimir
Great. That's exactly what I needed.
znq
+1  A: 

I can think of several ways that you could do this, each of which has some benefits (and drawbacks):

  • Have HttpClass post notifications in didReceiveResponse for which Class_A and Class_B could listen
  • Pass Class_A and Class_B as delegates to HttpClass, which would be called in didReceiveResponse
  • Use a target and action callback (very similar to the delegate approach)

Personally I would use delegates- it would make it simpler to add more functionality in the future and is more robust than using straight function pointers.

sbooth
Not sure how the first example would work, since I have various methods in the same class which need to be called back. The second solution is the same Vladimir suggested and that's what I implemented now. Works perfectly :-) The last one I read about here: http://goo.gl/VKBG but wasn't sure if this is only for UI elements. But as you said it's very similar to the delegat/selector approach. Thanks for the answer.
znq