#import "MainViewController.h"
@interface MainViewController ()
{
NSTimer *timer;
int i;
}
@end
@implementation MainViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self initView];
// Do any additional setup after loading the view.
}
- (void)viewDidUnload
{
[super viewDidUnload];
if (timer!=nil) {
if ([timer isValid]) {
[timer invalidate];
timer = nil;
}
}
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)dealloc{
[super dealloc];
}
#pragma mark - udf
- (void)initView{
UIButton *startTimer = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[startTimer setFrame:CGRectMake(124, 20, 72, 37)];
[startTimer setTitle:@"start timer" forState:UIControlStateNormal];
[startTimer addTarget:self action:@selector(startNSTimer:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:startTimer];
UIButton *stopTimer = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[stopTimer setFrame:CGRectMake(124, 75, 72, 37)];
[stopTimer setTitle:@"stop timer" forState:UIControlStateNormal];
[stopTimer addTarget:self action:@selector(stopNSTimer:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:stopTimer];
UIButton *fireTimer = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[fireTimer setFrame:CGRectMake(124, 130, 72, 37)];
[fireTimer setTitle:@"fire timer" forState:UIControlStateNormal];
[fireTimer addTarget:self action:@selector(fireNSTimer:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:fireTimer];
}
- (void)initTimer{
NSTimeInterval timeInteval = 5.0;
if (timer==nil) {
timer = [NSTimer scheduledTimerWithTimeInterval: timeInteval target:self selector:@selector(handleMaxShowTimer:) userInfo:nil repeats:YES];
}
}
#pragma mark - sel
- (void)handleMaxShowTimer:(NSTimer *)theTimer{
NSLog(@"NSTimer 调用%d",i++);
}
/*
*启动NSTimer
*/
- (void)startNSTimer:(id)sender{
[self initTimer];
}
/*
*调用NSTimer,直接执行
*/
- (void)fireNSTimer:(id)sender{
if (timer!=nil) {
if ([timer isValid]) {
[timer fire];
}
}
}
/*
*停止NSTimer,调用invalidate方法后,在把timer设置为nil,
*/
- (void)stopNSTimer:(id)sender{
if (timer!=nil) {
if ([timer isValid]) {
[timer invalidate];
timer = nil;
}
}
}
#pragma mark - callback
@end
转载于:https://my.oschina.net/simple2012/blog/102055