【发布时间】:2014-01-17 13:20:44
【问题描述】:
我正在尝试使用 AppDelegate 通过和 NSTimer 在视图控制器中触发委托方法。所以在AppDelegate中,我基本上有:
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; -
哦,我明白你的意思了......
-
在这个例子中我可以在哪里分配代理?
-
只要有可能 - 创建 ViewController 并将其分配为委托
标签: ios objective-c