【问题标题】:iOS - Setting delegate of input stream to another classiOS - 将输入流的委托设置为另一个类
【发布时间】:2013-09-03 10:45:01
【问题描述】:

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

【问题讨论】:

  • 你能解决这个问题吗?还是还开着?
  • 我搜索了委托机制,但后来我发现通知中心机制更适合我。我正在创建我的单例 TCPConnection 对象,当我从服务器获取输入并将通知发布到视图控制器类以处理响应并在界面中进行修改时。感谢您的建议。 :)

标签: ios delegates inputstream nsinputstream cfreadstream


【解决方案1】:

如果您的ViewController 正在响应NSStreamDelegate,您可以像往常一样启动控制器实例并设置委托。

@interface ViewController : NSOperation<NSStreamDelegate>
...

-

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

例如

更新:

TCPConnection 类中使用idUIViewController&lt;NSStreamDelegate&gt; 变量来保存父级。

例如:

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

并且只有一个此类的实例。大多数情况下是最好的方法;)

【讨论】:

  • 谢谢,但我认为这有点硬编码,因为在我的机制中,我想动态分配 ViewController。例如,我创建了一个名为 TCPConnection 的类,它具有 inputStream 和 outputStream 等属性。有了这个,我可以在我的项目中的每个ViewController 中创建这个对象。问题是,在 TCPConnection 类中,我如何知道哪个ViewController 创建了TCPConnection 对象,以便我可以将ViewController 设置为委托。我说清楚了吗? :)
  • 您可以将创建实例的类传递给您的 TCPConnection(id 父级)。已经考虑过单例解决方案在这里是否会很好?所以只有你的 TCPConnection 处理一切,只是由其他类调整? ;)
  • 感谢您的建议,我会考虑的。 :)
  • 更新了一个分配父母的例子。希望你知道单例是如何工作的。通过具体问题随时提出;)如果它帮助你,请接受和/或投票:)
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-09
    • 2015-12-08
    • 1970-01-01
    相关资源
    最近更新 更多