我有一个有代表的课程:
@protocol SNIRCControllerDelegate
- (void) serverTalked:(id)data;
@end
@interface SNIRCController : NSObject <NSStreamDelegate> {
id<SNIRCControllerDelegate> delegate;
}
- (void) setDelegate:(id<SNIRCControllerDelegate>)_delegate;
- (void) test;
@end
实施:
@implementation SNIRCController
- (void) setDelegate:(id<SNIRCControllerDelegate>)_delegate {
_delegate = delegate;
}
- (void) test {
[delegate serverTalked:@"test"];
}
但由于某种原因[delegate serverTalked:@"test"];
没有调用委托:/
这就是我在AppDelegate上的表现:
@interface AppDelegate : NSObject <NSApplicationDelegate, NSStreamDelegate, SNIRCControllerDelegate> {
IBOutlet NSTextView *logField;
SNIRCController *ircController;
}
@property (assign) IBOutlet NSWindow *window;
-(void)writeToLog:(NSString*)data;
@end
@implementation AppDelegate
@synthesize window = _window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
ircController = [[SNIRCController alloc] init];
[ircController setDelegate:self];
[ircController test];
}
- (void) serverTalked:(id)data {
NSLog(@"got called :D");
}
-(void)writeToLog:(NSString*)data {
NSAttributedString *stringToAppend = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n", data]];
[[logField textStorage] appendAttributedString:stringToAppend];
}
但serverTalked:
没有被调用:(我做错了什么?
答案 0 :(得分:2)
在setDelegate:
的实施中,这个:
_delegate = delegate;
应该是:
delegate = _delegate;
你感到困惑并交换了ivar和参数。这种混淆可能是因为下划线前缀更常用于ivars。在您的情况下,它是以下划线为前缀的参数。