簡體   English   中英

NSTimer在不同功能中使用時不起作用

[英]NSTimer not working when used in different functions

當我像這樣使用它時,ns計時器工作,即它同時調用foo1和foo1

-(void)register1
{
    NSRunLoop * runLoop = [NSRunLoop currentRunLoop];
    [runLoop addTimer:[NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(foo) userInfo:nil repeats:YES] forMode:NSDefaultRunLoopMode];
     [runLoop addTimer:[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(foo2) userInfo:nil repeats:YES] forMode:NSDefaultRunLoopMode];
    [runLoop run];
}

但我的要求是我必須在不同的函數中使用nstimer才能創建兩者的nsoperation。下面的代碼僅調用第一個函數。即,當我從main調用register1和register2時,僅注冊了一個定時器。

-(void)register1
{
    NSRunLoop * runLoop = [NSRunLoop currentRunLoop];
    [runLoop addTimer:[NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(foo) userInfo:nil repeats:YES] forMode:NSDefaultRunLoopMode];

    [runLoop run];
}
-(void)register2
{

    NSRunLoop * runLoop = [NSRunLoop currentRunLoop];
    [runLoop addTimer:[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(foo2) userInfo:nil repeats:YES] forMode:NSDefaultRunLoopMode];
    [runLoop run];
}

我已經找到了問題的答案,我也應該告訴其他人。解決方案是我必須為每個函數使用不同的線程。

abc *ab=[[abc alloc]init];
//[ab register1];
  //  [ab register2];


    NSOperationQueue *queue=[[NSOperationQueue alloc]init];
    NSInvocationOperation *abc=[[NSInvocationOperation alloc]initWithTarget:ab selector:@selector(register1) object:(nil)];
    NSInvocationOperation *abc2=[[NSInvocationOperation alloc]initWithTarget:ab selector:@selector(register2) object:(nil)];
   [queue addOperation:abc];
    [queue addOperation:abc2];
  1. 使用+[NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:]時,請勿調用-[NSRunLoop addTimer:forMode:] +[NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:] -這是多余的。 名稱的計划部分說明了一切:它正在創建一個定時器,該定時器已經為您安排在當前運行循環中。
  2. 通常不要調用-[NSRunLoop run] 它無限期地運行運行循環。 它基本上永遠不會返回。 因此,實際上不會調用第二個函數,因為您永遠不會從第一個函數返回。 您可以通過在各個位置插入NSLog語句或在調試器中單步執行代碼來簡單地確認這一點。

如果您發布了更多代碼,尤其是main()函數,那么我們可以為您提供更多答案。 通常,您只想從main()調用-[NSRunLoop run](或其變體)。

你可以這樣獲得NSTimer的點地址

NSTimer NSTimer * aTimer = [NSTimercheduledTimerWithTimeInterval:10 target:self選擇器:@selector(foo)userInfo:nil重復:是] forMode:NSDefaultRunLoopMode];

並將其用於另一種方法。

暫無
暫無

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

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