听起来您希望多个对象接收委托方法,对吗?在 Mac OS X 上,解决方案是使用通知系统。我没有看过这个AsyncSocket
类,但它看起来只支持开箱即用的委托。
通知很棒,因为它们让一个对象将信息广播给任何其他有兴趣接收它的对象。对象在通知中心注册自己,以便在发布特定通知时得到通知。您可以通过实现自己的类来轻松添加此功能 wrap AsyncSocket
。
这就是你要做的。您将编写自己的类,该类具有AsyncSocket
作为实例变量。您可以将此类设置为AsyncSocket
对象的委托。然后,当调用委托方法时,您会将通知发布到NSNotificationCenter
. 您可能需要将委托方法中的参数填充到通知的userInfo
字典中。
另一方面,您的视图控制器将NSNotificationCenter
作为观察者注册您的自定义类发送的通知。然后,每次委托方法触发时,每个视图控制器都会收到该事件的通知。
说够了;这是一些代码:
extern NSString *const AsyncSocketDidReadData;
@interface MySocketWrapper : NSObject { // give this class a better name ;-)
AsyncSocket *socket;
}
@property (nonatomic, readonly) socket;
@end
在 .m 文件中:
NSString *const AsyncSocketDidReadData = @"AsyncSocketDidReadData";
@implementation MySocketWrapper
@synthesize socket;
- (id)init {
if (![super init]) return nil;
socket = [[AsyncSocket alloc] init]; // initialize this however you want
[socket setDelegate:self];
return self;
}
- (void)onSocket:(AsyncSocket *)aSocket didReadData:(NSData *)data withTag:(long)tag {
NSDictionary *userInfo =
[NSDictionary dictionaryWithObjectsAndKeys:
data, @"data",
[NSNumber numberWithLong:tag], @"tag",
nil];
[[NSNotificationCenter defaultCenter] postNotificationName:AsyncSocketDidReadData object:self.socket userInfo:userInfo];
}
@end
最后,在您的各种视图控制器中,您可以编写如下代码:
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)bundle {
if (![super initWithNibName:nibName bundle:bundle]) return nil;
// Do any initalization you need here
// Note that if you specify 'nil' for object, you'll be sent notifications for every MySocketWrapper object.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(asyncSocketDidReadData:) notification:AsyncSocketDidReadData object:nil];
return self;
}
- (void)asyncSocketDidReadData:(NSNotification *)notification {
AsyncSocket *socket = [[notification object] socket];
NSData *theData = [[notification userInfo] objectForKey:@"data"];
long tag = [[[notification userInfo] objectForKey:@"tag"] longValue];
// Do what you want with the data here
}
显然,这段代码并不完全完整,而且我可能弄错了一些方法名称(我是凭记忆做的),但这是一个适合您的解决方案。