iOS - Setting delegate of input stream to another class

1.8k views Asked by At

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.

2

There are 2 answers

4
geo On BEST ANSWER

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 ;)

0
Deepak Kumar On

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