簡體   English   中英

從Appdelegate觸發ViewController中的委托方法

[英]Triggering delegate method in ViewController from Appdelegate

我正在嘗試使用AppDelegate通過NSTimer在viewcontroller中觸發委托方法。 因此,在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已成功觸發,但未觸發委托方法。

您在哪里將VC分配為代表? 是您的VC在初始化/加載視圖期間分配自身嗎? 如果您不這樣做,我會在ViewDidLoad中分配它。

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

另外,您可能希望將AppDelegate中的屬性設置為弱而不是強,以避免/如果VC被禁用則保留VC。

采用:

[[UIApplication sharedApplication].testDelegate = self;

而不是所有:

self.appDelegate = [[UIApplication sharedApplication] delegate];
self.appDelegate.testDelegate = self;

您的函數聲明為:

-(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"];
    }
});

檢查像

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

如果控制器在導航控制器中,則循環遍歷並找到控制器的活動對象並分配委托。

但是我會推薦使用LocalNotification的這種功能

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM