定时器 每一分钟调用一次 NSTimer-定时器的使用浅析

此帖转载别人的 贞娃儿 他的博客http://blog.sina.com.cn/s/blog_7b9d64af0101caaz.html
定时器
NSTimer 是做什么的? 我只是当做笔记,请勿喷,自己使用了,很好使用,有疑问可以交流

你想重复的执行一个特定任务,这个任务具有一定的延时。例如:只要你的程序在运行,你想每秒钟更新一次屏幕中的视图。 


1.在*.h 文件中定义一个定时器

@property (nonatomic,strong) NSTimer *paintingTimer;


2.在*.m中调用吧

//定时器执行的方法

-(void)paint:(NSTimer *)paramTimer{


   NSLog(@"定时器执行的方法");

}


//开始定时器

-(void) startPainting{

    

   // 定义一个NSTimer

   self.paintingTimer = [NSTimerscheduledTimerWithTimeInterval:1.0

                                                 target:self

                                               selector:@selector(paint:) userInfo:nil

                                                repeats:YES];

}


//停止定时器

-(void) stopPainting{

    if (self.paintingTimer != nil){

       // 定时器调用invalidate后,就会自动执行release方法。不需要在显示的调用release方法

       [self.paintingTimer invalidate];

    }

}


-(void)viewDidAppear:(BOOL)animated{

    

   [selfstartPainting];// 开始定时器

  

}


-(void)viewDidDisappear:(BOOL)animated{

    

 [selfstopPainting];// 停止定时器


}


NSTimer的初始化方法<一>

scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:方法


+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)secondstarget:(id)targetselector:(SEL)aSelectoruserInfo:(id)userInforepeats:(BOOL)repeats


seconds:需要调用的毫秒数

target:调用方法需要发送的对象。即:发给谁

userInfo:发送的参数

repeats:指定定时器是否重复调用目标方法


在看一看输出:

 Painting

 Main Thread = {name = (null), num = 1}

 Current Thread = {name = (null), num =1}

 Painting

 Main Thread = {name = (null), num = 1}

 Current Thread = {name = (null), num =1}


发现一个问题,呵呵
全部都是主线程在执行,那样的话,就有点问题了,我们应该让它在其他线程来执行!你懂的!我想用Block或者Operation都能够解决这个事情吧。那就过吧~~~扯得有点跑题了!

现在做个比喻:

我们可以把调度一个计时器与启动汽车的引擎相比较。别调度的计时器就是运行中的引擎。没有被调度的计时器就是一个已经准备好启动但是还没有运行的引擎。我们在程序里面,无论何时,都可以调度和取消调度计时器,就像根据我们所处的环境,决定汽车的引擎室启动还是停止。如果你想要在程序中,手动的在某一个确定时间点调度计时器,可以使用NSTimer的类方法 timerWithTimeInterval:target:selector:userInfo:repeats:方法。

飘红部分!说的好经典!
以上的程序,确实,我们能够调用和停止定时器,但是,我们还不够“ 随心所欲”。因为 NSTimer在初始化后就马上开始执行了!!!

NSTimer的初始化方法<二>

如果,我们想在任何时候都能够随心所欲的 启动/停止 定时器。

咋办?不用急,还有 NSTimer的另一种初始化方法,能够满足我们的要求:

贴吧!

// 使用 timerWithTimeInterval 方法来实例化一个 NSTimer, 这时候 NSTimer 是不会启动的

self.paintingTimer = [NSTimer timerWithTimeInterval:1.0

                                         target:self

                                       selector:@selector(paint:)

                                       userInfo:nil

                                        repeats:YES];



//当需要调用时,可以把计时器添加到事件处理循环中

 [[NSRunLoop currentRunLoop]addTimer:self.paintingTimer forMode:NSDefaultRunLoopMode];


忽然想问一句:NSRunLoop是什么?
循环运行!就像是程序的中枢神经,一直在运转着,并且监视着程序各种的事件、线程等等。
一旦出现了相关的事件,那么就开始调度,分配适当的对象来执行适当的操作!

NSTimer的初始化方法<三>

我们也可以用 timerWithTimeInterval方式来创建一个 NSTimer

贴:

-(void) startPainting{

   // 定义将调用的方法

    SEL selectorToCall = @selector(paint:);

   // SEL进行方法签名

    NSMethodSignature*methodSignature=[[self class]instanceMethodSignatureForSelector:selectorToCall];

   // 初始化NSInvocation

    NSInvocation *invocation =[NSInvocationinvocationWithMethodSignature:methodSignature];

    [invocation setTarget:self];

   [invocation setSelector:selectorToCall];

    self.paintingTimer = [NSTimer timerWithTimeInterval:1.0

                                      invocation:invocation

                                        repeats:YES];

    

// 当需要调用时,可以把计时器添加到事件处理循环中

    [[NSRunLoop currentRunLoop] addTimer:self.paintingTimer forMode:NSDefaultRunLoopMode];

}


忽然想问一句: NSInvocation 是什么?

是Object-C中的消息传递着。它可以以“方法签名”的方式来封装一个对象的方法,并且在各个对象中传送!主要可以用在NSTimer中。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这里提供一个简单的红包雨功能的object-c实现示例: 首先,我们需要准备红包图片的资源,用UIImageView来展示红包。 ```objective-c // 初始化红包图片视图 UIImageView *redPacketImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -50, 50, 50)]; redPacketImageView.image = [UIImage imageNamed:@"redPacket.png"]; [self.view addSubview:redPacketImageView]; ``` 接下来,我们需要实现红包的下落动画,让它从上面飘落到下面。 ```objective-c // 定义红包下落动画 CABasicAnimation *fallingAnimation = [CABasicAnimation animationWithKeyPath:@"position.y"]; fallingAnimation.fromValue = [NSNumber numberWithFloat:-50]; fallingAnimation.toValue = [NSNumber numberWithFloat:self.view.bounds.size.height + 50]; fallingAnimation.duration = 5.0; fallingAnimation.delegate = self; // 添加红包下落动画 [redPacketImageView.layer addAnimation:fallingAnimation forKey:@"fallingAnimation"]; ``` 我们同时需要处理多个红包的下落逻辑,可以使用NSTimer定时器来实现。 ```objective-c // 定义红包定时器 NSTimer *redPacketTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(addRedPacket) userInfo:nil repeats:YES]; // 添加红包方法 - (void)addRedPacket { // 初始化红包图片视图 UIImageView *redPacketImageView = [[UIImageView alloc] initWithFrame:CGRectMake(arc4random_uniform((uint32_t)self.view.bounds.size.width - 50), -50, 50, 50)]; redPacketImageView.image = [UIImage imageNamed:@"redPacket.png"]; [self.view addSubview:redPacketImageView]; // 定义红包下落动画 CABasicAnimation *fallingAnimation = [CABasicAnimation animationWithKeyPath:@"position.y"]; fallingAnimation.fromValue = [NSNumber numberWithFloat:-50]; fallingAnimation.toValue = [NSNumber numberWithFloat:self.view.bounds.size.height + 50]; fallingAnimation.duration = 5.0; fallingAnimation.delegate = self; // 添加红包下落动画 [redPacketImageView.layer addAnimation:fallingAnimation forKey:@"fallingAnimation"]; } ``` 最后,我们需要处理红包落地后的逻辑,让用户可以获得奖励。 ```objective-c // 红包下落动画结束后回调方法 - (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag { // 判断是否是红包下落动画 if ([redPacketImageView.layer animationForKey:@"fallingAnimation"] == anim) { // 移除红包图片视图 [redPacketImageView removeFromSuperview]; // 弹出获得奖励提示框 UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"恭喜您获得奖励!" message:@"获得了10元现金红包!" preferredStyle:UIAlertControllerStyleAlert]; [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]]; [self presentViewController:alertController animated:YES completion:nil]; } } ``` 这样就实现了一个简单的红包雨功能。当用户进入红包雨页面后,红包会不断从上面飘落到下面,并且用户可以获取奖励。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值