ios开发笔记-循环调用/执行一个方法

转自: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

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


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值