2012-12-02 45 views
2

我刚学习使用Objective-C,并尝试使用NSTimer与scheduledTime间隔没有运气。我使用的外观的代码如下:获取NSTimer调用方法的问题

#import <Foundation/Foundation.h> 
#import "timerNumber1.h" 

int main(int argc, const char * argv[]) 
{ 
@autoreleasepool { 

    NSTimer *timerNumber1; 

    NSInteger counter=0; 

    while (counter<5){ 


     timerNumber1 = [NSTimer scheduledTimerWithTimeInterval:1 target:timerNumber1 selector: @selector(updateTimer:) userInfo:nil repeats:YES]; 

    NSLog(@"Hello, World!"); 
     counter++; 
    } 
} 
return 0; 
} 

timerNumber1头看起来如下

#import <Foundation/Foundation.h> 

@interface timerNumber1 : NSObject 
-(void) updateTimer; 

@end 

和实施

#import "timerNumber1.h" 

@implementation timerNumber1 

-(void) updateTimer{ 
NSLog(@"Timer Updated!"); 

} 
@end 

的方法似乎从来没有火,我从来没有看到计时器更新。
我在这里做错了什么?

回答

0

变量timerNumber1尚未初始化(可能是nil),所以target参数不会有效。将在nil对象上调用updateTimer方法,该对象在Objective-C中静默失败。

您需要先创建对象,然后才能按照您的操作进行操作。

旁注:有一个与您的变量名称完全相同的类有点不寻常。这通常不是一个好主意,至少出于可读性的原因。另外,由于您有repeats:YES,因此我不能100%确定您需要为每次重复创建一个计时器。但是我会让你成为你想要对你的代码做什么的评判者。 :-)

编辑:刚刚注意到别的东西,选择器可能有点偏离 - 选择器中有:,但updateTimer不带任何参数。在那种情况下,我认为那里不应该有冒号。

因此,尝试这样的事情:

int main(int argc, const char * argv[]) 
{ 
    @autoreleasepool { 

     NSTimer *timer; 
     timerNumber1 *timerNumber1Object = [[timerNumber1 alloc] init]; 

     NSInteger counter=0; 

     while (counter<5){ 
      timer = [NSTimer scheduledTimerWithTimeInterval:1 target:timerNumber1Object selector: @selector(updateTimer) userInfo:nil repeats:YES]; 

      NSLog(@"Hello, World!"); 
      counter++; 
     } 
    } 
    return 0; 
} 
+2

将是非常好的,如果人们会后与他们的反对票的理由的评论让谁张贴答案的人可以完善自己。有点叫做*建设性的批评*。 : - | –

+0

while循环的原因是允许定时器运行。不过,我认为我需要成为一名运动员。我试着删除while循环,并在头文件中使用NSTimer而不是NSObject。但是我仍然得到相同的结果。 – user1870561

+0

代码现在看起来像这样: – user1870561