iOS - 将输入流的委托设置为另一个类

时间:2013-09-03 10:45:02

标签: ios delegates inputstream nsinputstream cfreadstream

我想知道如果可以将输入流的委托设置为另一个类。到目前为止,我遇到的所有例子都是自我: [inputStream setDelegate:self]。 我想将委托设置为另一个类,如ViewController而非自我。提前谢谢。

2 个答案:

答案 0 :(得分:2)

如果ViewController正在回复NSStreamDelegate,您可以启动控制器实例并照常设置代理。

@interface ViewController : NSOperation<NSStreamDelegate>
...

-

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

例如

更新

使用UIViewController<NSStreamDelegate>类中的 id TCPConnection变量来保存父级。

例如:

// 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];

或者是一个单独的解决方案,你总是只打电话给

TCPConnection *connection = [TCPConnection sharedInstance];

并且只有这个类的一个实例。在大多数情况下最好的方式;)

答案 1 :(得分:0)

您可以对委托进行类型转换并将其设置为某个特定的委托,然后调用该委托。