iOS - 将输入流的代理设置为另一个类 [英] iOS - Setting delegate of input stream to another class

查看:213
本文介绍了iOS - 将输入流的代理设置为另一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如果可以将输入流的委托设置为另一个类。到目前为止,我遇到的所有例子都是self:
[inputStream setDelegate:self]
我想将代理设置为另一个类,如 ViewController 不是自己。如果您的 ViewController 正在响应<$($)$ $ $ $ $ $ $ $ $ code> NSStreamDelegate ,您可以启动控制器的实例并照常设置代理。

  @interface ViewController:NSOperation< NSStreamDelegate> 
...

-

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

例如



更新:



使用 id UIViewController< NSStreamDelegate> 要保存父级的 TCPConnection 类。



例如:

  // TCPConnection.h 

@interface TCPConnection:NSOperation< NSStreamDelegate>

@property(nonatomic,assign)UIViewController< NSStreamDelegate>父母

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

...

  // TCPConnection.m 

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

// UIViewController< NSStreamDelegate> .m

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

或一个singlton解决方案,你总是只呼叫

  TCPConnection * connection = [TCPConnection sharedInstance]; 

,只有这个类的一个实例。对于大多数情况下最好的方法;)


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.

解决方案

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

这篇关于iOS - 将输入流的代理设置为另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆