I am using AsyncSocket for a TCP connection.
I have one TCP socket, but I have two UIViewControllers use this socket.
As I know, there is only one delegate while I init the AsyncSocket.
These two UIViewControllers both need to handle the callback from the AsyncSocket.
Is there any good idea to achieve this?
Any idea is appreciated!
Asked
Active
Viewed 255 times
0

srjohnhuang
- 232
- 5
- 18
2 Answers
0
When you need to have multiple delegates for something you can use any of theses:
- Have some
manager
class to act as the delegate for the Socket. This manager class would have an array of delegates (a simple NSArray where each element is of typeid<someCustomDelegate>
). Additionally you have asomeCustomDelegate
protocol that each one of your Viewcontrollers implement. when the delegate method of your AsyncSocket is invoked, you iterate through the array of custom delegates to notify each one of the subscribed ViewControllers. - You can have a similar pattern to number 1, but instead of an array of delegates, you just post a custom notification, and make each ViewController listen for that particular notification. This approach would be easier and is also very reliable.

Merlevede
- 8,140
- 1
- 24
- 39
-
Thanks for your sharing! I would prefer your 2nd advice. I think your 1st method is a little complicated for me, but I would love to know more about it. Is there any similar example to this implementation? – srjohnhuang Mar 27 '14 at 05:46
-
I don't know of a particular example, but I'm sure if you google something like `array of delegates` you might find something. Also, it's not that difficult, provided you've worked with custom delegates before, the only new thing would be instead of having a delegate property you have an array. – Merlevede Mar 27 '14 at 05:49
-
Great! Thanks for your hint! I will try to google "array of delegates". – srjohnhuang Mar 27 '14 at 05:54
0
You can use nsnotificationcenter, to notify two view controllers about callback from AsyncSocket. You can use AsyncSocket code in some appcontroller (you may create it for your app)/appdelegate. when it fires it callback you can sent Notification AsyncSocketNoftication (you have to create named notification like this) which is captured by respective viewcontroller which are listening to AsyncSocketNoftication. this is useful even you want to notify many number of viewcontrollers.
Hope it helps !
-
Thanks for your quick response. It seems using the nsnotificationcenter is a good approach. Do you think it is a good idea to using the AsyncSocket in AppDelegate? Or using the AsyncSocket in a separated manager UIViewController? – srjohnhuang Mar 27 '14 at 05:35
-
It depends on how your application moves around your AsyncSocket part.Depending on your need you can decide which is best place to put this code. AppDelegate is just my suggestion.just give thought for placing this code. (Think->design->Implement) :) – jnix Mar 27 '14 at 05:47
-