2012-07-31 42 views
0

在我的應用程序中有兩個視圖。廠景有一個功能測試啓動和停止另一個視圖中的一個視圖的計時器

-(void) testing 
    { 
     NSLog(@"Testing : %d", (++x)); 
    } 

和計時器

timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(testing) userInfo:nil repeats:YES]; 

我想要什麼,是停止和運行與視圖2此計時器。怎麼做 ?

+0

創建''timerV2'在ivar''view2'然後傳遞'timer'到'view2' – 2012-07-31 05:29:14

+0

可以請你寫代碼,因爲我是新來的Objectice C – 2012-07-31 05:33:25

回答

5

在AppDelegate中定義定時器,

@interface TimerDemoAppDelegate : NSObject <UIApplicationDelegate> 
{ 
NSTimer *timer; 
} 

@property (nonatomic, retain) NSTimer *timer; 

@end 

,並通過創建TimerDemoAppDelegate使用定時器您同時查看對象 在你看來.H在你看來.m文件

appDelegate=(TimerDemoAppDelegate *)[[UIApplication sharedApplication] delegate]; 

現在使用定時器作爲appDelegate.timer文件

@interface View1 : UIViewController 
{ 
TimerDemoAppDelegate *appDelegate; 
} 

0

添加timer2View2

@interface View2 : UIView{ 
    NSTimer *timer2; 
} 
@property (nonatomic,retain) NSTimer *timer2; 
@end 


@implementation View2 
@synthesize timer2; 
@end 

,做這樣的

timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(testing) userInfo:nil repeats:YES]; 
view2.timer2 = timer; 
+0

非常感謝。這是非常有幫助的... – 2012-07-31 05:48:15

+0

我的樂趣夥計.. – 2012-07-31 06:03:11

0

使用NSNotificationCenter您可以在不創建任何對象的情況下從其他視圖調用方法。

在你viewDidLoad

[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(button:) 
              name:@"Next" 
              object:nil]; 

-(void)button:(NSNotification *) notification 
{ 
// write a code of timer here..... 
} 


//call this following from another view 

[[NSNotificationCenter defaultCenter] 
postNotificationName:@"Next" 
object:self]; 

享受此代碼....

相關問題