I have a simple delegate test, but for some reason it doesn’t get called.
I want to call -(void)test from AppDelegate class via delegate.
/// AppDelegate.h
#import <Cocoa/Cocoa.h>
@protocol AppDelegateDelegate
@required
-(void)test;
@end
@interface AppDelegate : NSObject <NSApplicationDelegate> {
id<AppDelegateDelegate> _delegate;
}
@property(nonatomic, retain) id<AppDelegateDelegate> delegate;
@end
/// AppDelegate.m
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize delegate = _delegate;
-(void)awakeFromNib {
[_delegate test];
}
@end
/// test.h
#import <Foundation/Foundation.h>
#import "AppDelegate.h"
@interface test : NSObject <AppDelegateDelegate>
-(void)test;
@end
/// test.m
#import "test.h"
@implementation test
-(void)test {
//this should be called from AppDelegate
NSLog(@"delegate test");
}
@end
You are calling the delegate
testmethod as soon as theAppDelegateclass is loaded and no other class has had a chance to set themselves as the delegate. You need to call the delegate method after another class has had a chance to set itself as the delegate.Also your delegate property should be defined as: