在Cocoaasyncsocket中将委托设置为另一个对象

时间:2015-07-13 00:23:20

标签: ios objective-c delegates

我试图编写一个可以发送和接收数据的简单UDP客户端,我想将委托设置为除self之外的另一个对象。

我能够发送数据,但无法从服务器接收任何回传。服务器工作正常。

我的代码如下:

//ViewController.m
- (void)setupSocket
{

    UDPReveiver * udp = [[UDPReveiver alloc] init];
    udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:udp delegateQueue:dispatch_get_main_queue()];

    NSError *error = nil;

    if (![udpSocket bindToPort:5528 error:&error])
    {
        NSLog(@"Error binding: %@", error);
        return;
    }
    if (![udpSocket beginReceiving:&error])
    {
        NSLog(@"Error receiving: %@", error);
        return;
    }

    NSLog(@"Socket Created :)");
}

//UDPReceiver.h

@interface UDPReveiver : NSObject <GCDAsyncUdpSocketDelegate>

//UDPReceiver.m

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
  fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
    NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"Hey");
    if (msg)
    {
        NSLog(@"Data received is :%@",msg);
    }
}

请让我知道我错过了什么。

1 个答案:

答案 0 :(得分:0)

问题是当B6超出范围时会立即释放它。某些对象(例如创建UDPReveiver *udp的视图控制器)可能需要是该委托的所有者,并将其保留在udp属性中。这使得udp实例的保留计数大于零,从而保持不变。所以...

strong

然后你的设置......

// in the ViewController's interface...
@property(strong, nonatomic) UDPReveiver *udp;

完成套接字后,视图控制器可以丢弃代理,如下所示:

- (void)setupSocket
{
    self.udp = [[UDPReveiver alloc] init];
    udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self.udp delegateQueue:dispatch_get_main_queue()];

    // and so on

...或者在视图控制器被释放时它将被释放。