我試圖通過和NSTimer在視圖控制器中使用AppDelegate觸發委託方法。所以在AppDelegate中,我主要有:從AppDelegate在ViewController中觸發委託方法
AppDelegate.h
@protocol TestDelegate <NSObject>
-(void)testFunction:(NSString *)testString;
@end
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) id<TestDelegate> testDelegate;
...
@end
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self.window makeKeyAndVisible];
self.timer = [NSTimer scheduledTimerWithTimeInterval:10.0
target:self
selector:@selector(trigger:)
userInfo:nil
repeats:YES];
return YES;
}
-(void)trigger:(id)sender {
[self.testDelegate testFunction:self];
}
在我的視圖控制器我有:
ViewController.h
@interface ViewController : UIViewController <TestDelegate>
@property (nonatomic, strong) AppDelegate *appDelegate;
@end
ViewController.m
@implementation ViewController
...
-(void)viewDidLoad {
self.appDelegate = [[UIApplication sharedApplication] delegate];
self.appDelegate.testDelegate = self;
}
-(void)testfunction:(NSString *)testString {
NSLog(@"%@", testString);
}
@end
當我在我的應用程序中加載ViewController時,什麼都沒有發生?我知道NSTimer正在成功觸發,但委託方法沒有被觸發。
你在哪裏分配什麼testDelegate? –
在我的appdelegate.h中,我有@property(strong,nonatomic)id testDelegate; –
Allen
哦,我明白你的意思了...... – Allen