2011-11-08 60 views
0

我在学习有关NSTimer和读完文档后,我做了这个简单的测试。我的理解是,当我在main中调用viewDidLoad时,viewDidLoad应该在3.0秒后调用runTest - 但它不起作用。它编译罚款没有错误,但不会加载runTest(没有NSLog)请帮助...谢谢。简单的NSTimer测试不起作用

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

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

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 

MyClass *trial = [[MyClass alloc]init]; 

[trial viewDidLoad]; ///// this should call viewDidLoad ///// 

[pool drain]; 
return 0; 
} 



#import <Foundation/Foundation.h> 

@interface MyClass : NSObject { 

NSTimer *aTimer;} 

@property (nonatomic, retain) NSTimer *aTimer; 

- (void)viewDidLoad; 

- (void)runTest; 

@end 





#import "MyClass.h" 

@implementation MyClass 

@synthesize aTimer; 

- (void)viewDidLoad { 
    aTimer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self  selector:@selector(runTest) userInfo:nil repeats:NO];} 

- (void) runTest { 
NSLog(@"Working - runTest has loaded !"); 
aTimer = nil; 
} 
@end 
+0

你确定你在调用viewDidLoad吗? – jbat100

回答

2

它不会这样工作。 NSTimer需要一个runloop,当你制作一个普通的Cocoa应用程序而不是一个Foundation命令行工具时,它会自动创建。

如果在主要笔尖中实例化该对象,请在对象的代理的applicationDidFinishLaunching方法或对象的init中创建计时器。

+0

你是说在生产控制台小应用程序时,NSTimer不能以任何形式使用?如果是的话,applicationDidFinishLaunching的一个小例子会很棒。 – pete

+0

只需制作一个新的可可应用程序并转到AppDelegate类。你会看到' - (void)applicationDidFinishLaunching:(NSNotification *)aNotification'方法。 – Davyd