委托方法未被触发

时间:2011-04-27 15:41:32

标签: cocoa-touch delegates

我可以想到的任何问题都会被检出,但代理方法仍然不会触发。我在Socket.h中声明了一个名为SocketDelegate的协议:

@protocol SocketDelegate <NSObject>
@optional
- (void)socket:(Socket *)socket handleNewConnection:(NSString *)test;
- (void)socket:(Socket *)socket didSend:(BOOL)didSend;
- (void)socket:(Socket *)socket didReceive:(BOOL)didReceive;
@end

@interface Socket : NSObject {
    id<SocketDelegate> delegate;
}

@property(nonatomic,assign) id<SocketDelegate> delegate;

@end

现在,在Socket.m中,代理会收到发送/接收文件成功/错误的通知:

@implementation Socket

/* I checked: both of these methods are called */

- (void)stopSendWithStatus:(NSString *)statusString {
    [self.delegate socket:self didSend:isSent];
}

- (void)stopReceiveWithStatus:(NSString *)statusString {
    [self.delegate socket:self didReceive:isReceived];
}

@end

ViewController.h符合代表:

@interface ViewController : UIViewController <SocketDelegate>

并在ViewController.m中,我通过将Socket和ViewController链接在一起的NetController类设置委托。我实现了委托方法:

@implementation ViewController

- (void)viewDidLoad {
    /* I checked: this method is called */
    /* Both 'netController' and 'socket' are initialized correctly
    netController = [[NetController alloc] init];
    [[netController socket] setDelegate:self];  
}

@end

@implementation ViewController (SocketDelegate)

- (void)socket:(Socket *)socket didSend:(BOOL)didSend {
    NSLog(@"didSend %@", didSend);        // Nothing happens...
}

- (void)socket:(Socket *)socket didReceive:(BOOL)didReceive {
    NSLog(@"didReceive %@", didReceive);  // Nothing happens...
}

@end

另外,我试图在ViewController.m中设置除viewDidLoad之外的其他地方,但它没有任何效果。当然我没有编译器错误,也没有运行时错误......我的代码出了什么问题?

2 个答案:

答案 0 :(得分:0)

您确定调用了-viewDidLoad吗?你的ViewController课不会继承任何东西,我想你想做:

@interface ViewController : UIViewController <SocketDelegate>

确保调用-viewDidLoad,如果不是,则可能尚未连接到NIB文件或以编程方式创建。下一步,确保套接字函数正在尝试调用委托函数。此外,Socket类也没有从任何东西继承,我不知道你如何在netController中构造你的socket,但我不得不改为

@interface Socket : NSObject

以便能够构造一个对象。确保正确构造netController中的套接字对象。请记住,如果它们为零,则在您尝试向其发送消息时不会发出警告。

修复所有这些事情,这对我有用。

答案 1 :(得分:0)

我的猜测是套接字本身(它是NetController对象的一部分)未正确初始化,或在触发委托调用之前被释放。如何初始化作为NetController对象一部分的套接字?