转自:https://lwxshow.com/post/1123.html
用两种方法可以实现循环的调用一个方法:
1.使用NSTimer
1.1TestViewController.h文件代码如下
#import <UIKit/UIKit.h>
@interface TestViewController:UIViewControlller{
NSTimer *theTimer;
}
- (void)executeTest;//要多次循环的方法
- (void)initializetion;//初始化方法
@end
1.2TestViewController.m文件代码如下
2.使用QuartzCore framwork中的 CADisplayLink#import "TestViewController"
@implementation TestViewController
//在viewDidLoad中添加初始化
- (void)viewDidLoad{
[self initializetion];
}
//实现方法
- (void)initializetion{
if (theTimer == nil){
float theInterval = 1.0f/30.0f;//1秒执行30次
theTimer = [NSTimer scheduledTimerWithTimeInterval:theInterval
target:self selector:@selector(executeTest) userInfo:nil repeats:YES];
}
}
- (void)executeTest{
NSLog(@"test excute");
}
@end
#import "TestViewController"
@implementation TestViewController
//在viewDidLoad中添加初始化
- (void)viewDidLoad{
[self initializetion];
}
//实现方法
- (void)initializetion{
if (theTimer == nil){
float theInterval = 1.0f/30.0f;//1秒执行30次
theTimer = [NSTimer scheduledTimerWithTimeInterval:theInterval
target:self selector:@selector(executeTest) userInfo:nil repeats:YES];
}
}
- (void)executeTest{
NSLog(@"test excute");
}
@end
2.1添加QuartzCore框架添加到工程中,
点击工程-->build phasas->build framwork...->点击+号-->添加quartzcore框架
2.2TestViewController.h文件中代码如下:
#import <UIKit/UIKit.h>
#import <QuartzCore/CADisplayLink.h>
@interface TestViewController:UIViewControlller{
CADisplayLink *theTimer;
}
- (void)executeTest;//要多次循环的方法
- (void)initializetion;//初始化方法
@end
2.3TestViewController.m文件中的代码如下:
#import "TestViewController"
@implementation TestViewController
//在viewDidLoad中添加初始化
- (void)viewDidLoad{
[self initializetion];
}
//实现方法
- (void)initializetion{
if (theTimer == nil){
theTimer = [NSTimer displayLinkWithTarget:self selector:@selector(executeTest)];
theTimer.frameInterval = 2;//每秒执行30次,默认为60 ,=2的话就是除以2 =30
[theTimer addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
}
- (void)executeTest{
NSLog(@"test excute");
}
@end