2011-11-08 90 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