iOS - Setting delegate of input stream to another class

陌路散爱 提交于 2020-01-03 03:06:07

问题


i am wondering that if it is possible to set the delegate of input stream to another class. So far all examples i have encountered are with self: [inputStream setDelegate:self]. I want to set delegate to another class like a ViewController not self. Thanks in advance.


回答1:


if your ViewController is responding to NSStreamDelegate, you can initiate an instance of the controller and set the delegate as usual.

@interface ViewController : NSOperation<NSStreamDelegate>
...

-

ViewController *vc = [[ViewController alloc] init];
[inputStream setDelegate:vc];

for example

update:

use an id or UIViewController<NSStreamDelegate> variable in the TCPConnection class to hold the parent.

For example:

// TCPConnection.h

@interface TCPConnection : NSOperation<NSStreamDelegate>

@property(nonatomic, assign) UIViewController<NSStreamDelegate> parent;

-(id)initWithParent:(UIViewController<NSStreamDelegate> *)p_parent;
...

...

// TCPConnection.m

-(id)initWithParent:(UIViewController<NSStreamDelegate> *)p_parent
{
    self = [super init];
    self.parent = p_parent;
    return self;
}

// UIViewController<NSStreamDelegate>.m

TCPConnection *connection = [[TCPConnection alloc] initWithParent:self];

Or a singlton solution, where you always call only

TCPConnection *connection = [TCPConnection sharedInstance];

and have only one instance of this class. For the most cases the best way ;)




回答2:


You can typecast the delegate and set it to some particular delegate and that will get called.



来源:https://stackoverflow.com/questions/18590265/ios-setting-delegate-of-input-stream-to-another-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!