Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top