代表不会工作

时间:2012-07-28 08:34:35

标签: objective-c xcode delegates

我有一个简单的委托测试,但由于某种原因它不会被调用。

我想通过委托-(void)test课程致电 AppDelegate

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

1 个答案:

答案 0 :(得分:0)

加载test类后,您正在调用委托AppDelegate方法,并且没有其他类有机会将自己设置为委托。在另一个类有机会将自己设置为委托之后,您需要调用委托方法

您的委托属性也应定义为:

@property (assign) IBOutlet id <AppDelegateDelegate> delegate;