开发者

Function pointers in Objective-C

开发者 https://www.devze.com 2022-12-29 18:09 出处:网络
I have the following scenario: Class_A - method_U - method_V - method_X - method_Y Class_B - method_M - method_N

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开发者_Python百科 -> 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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消