2014-01-17 31 views
0

我試圖通過和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正在成功觸發,但委託方法沒有被觸發。

+0

你在哪裏分配什麼testDelegate? –

+0

在我的appdelegate.h中,我有@property(strong,nonatomic)id testDelegate; – Allen

+0

哦,我明白你的意思了...... – Allen

回答

1

你的函數聲明爲:

-(void)testFunction:(NSString *)testString; 

但是你怎麼稱呼它爲:

[self.testDelegate testFunction:self]; 

所以你發送self到一個參數期望指向NSString,這顯然是不正確的。

此外,而不是使用一個計時器,我會使用GCD,像這樣:

double delayInSeconds = 10.0; 
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); 

dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ 
    if [self.testDelegate respondsToSelector:@selector(testFunction:)] { 
     [self.testDelegate testFunction:@"Test String"]; 
    } 
}); 
+0

感謝您的答案,只是好奇,因爲我沒有得到一個簡潔的答案,但爲什麼GCD超過NSTimer?使用NSTimer有什麼缺點? – Allen

+0

另一個問題是爲什麼原始代碼編譯後,因爲有一個協議定義? – ahwulf

+0

@ahwulf它位於AppDelegate.h文件中,位於頂部。 – Abizern

0

檢查像

if(!testDelegate) { 
    [self.testDelegate testFunction:self]; 
} 

,如果你的控制器是在你的導航控制器來控制循環,找到你的控制器還活着的對象,並指定委託。

不過,我會建議使用LocalNotification

1

你在哪裏分配的VC爲代表這還挺功能?在初始化/視圖執行過程中,您的VC是否自行分配?如果你不這樣做,我會在ViewDidLoad中分配它。

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    [[UIApplication sharedApplication]delegate].testDelegate = self; 
} 

而且你可能會想設置在AppDelegate中弱而不強的財產,以避免保留VC當/如果它被駁回。

+0

我剛添加到viewcontroller的viewdidload,但它仍然不工作的原因? – Allen

+0

這應該是一個問題實際上 –

1

用途:

[[UIApplication sharedApplication].testDelegate = self; 

,而不是所有的:

self.appDelegate = [[UIApplication sharedApplication] delegate]; 
self.appDelegate.testDelegate = self; 
相關問題