0

私のアプリには2つのビューがあります。view1 には機能テストがあります

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

そしてタイマー

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

私が欲しいのは、view2からこのタイマーを停止して実行することです。どうやってするか ?

4

3 に答える 3

5

AppDelegateでタイマーを定義します。

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

@property (nonatomic, retain) NSTimer *timer;

@end

ビューの.hファイルにTimerDemoAppDelegateオブジェクトを作成して、両方のビューでタイマーを使用します

@interface View1 : UIViewController
{
TimerDemoAppDelegate *appDelegate;
}

ビューの.mファイル

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

appDelegate.timerとしてタイマーを使用するようになりました。

于 2012-07-31T05:51:14.797 に答える
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];

このコードでお楽しみください...

于 2012-07-31T05:56:11.067 に答える
0

クラスtimer2に追加View2

@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;
于 2012-07-31T05:39:08.003 に答える