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

Setting delegate to another object in Cocoaasyncsocket

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

我可以发送数据,但无法从服务器接收到任何返回数据。服务器运行正常。

我的代码如下:

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

请让我知道我缺少什么。

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

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

完成套接字后,您的视图控制器可以丢弃委托,如下所示:

self.udp = nil;

...或者在view controller释放的时候释放。