iOS 定时器

来源:互联网 发布:常见的时间序列算法 编辑:程序博客网 时间:2024/05/21 02:36

1NSTimer使用注意

1RunLoop的关系 

2)释放不掉的问题

http://blog.csdn.net/Christ_Beings/article/details/53425665


https://www.mgenware.com/blog/?p=459

 ***http://www.cocoachina.com/ios/20150710/12444.html


.h

//

//  HLWeakTimerTarget.h

//  ThreadTest

//

//  Created by Holly on 2017/12/4.

//  Copyright © 2017 Holly. All rights reserved.

//


#import <Foundation/Foundation.h>


@interface HLWeakTimerTarget : NSObject


@property (nonatomic, weak) id target;

@property (nonatomic, assign) SEL selector;

@property (nonatomic, weak) NSTimer* timer;


+ (NSTimer *) scheduledTimerWithTimeInterval:(NSTimeInterval)interval

                                      target:(id)aTarget

                                    selector:(SEL)aSelector

                                    userInfo:(id)userInfo

                                     repeats:(BOOL)repeats;

@end



.m

//

//  HLWeakTimerTarget.m

//  ThreadTest

//

//  Created by Holly on 2017/12/4.

//  Copyright © 2017 Holly. All rights reserved.

//


#import "HLWeakTimerTarget.h"


@implementation HLWeakTimerTarget


+ (NSTimer *) scheduledTimerWithTimeInterval:(NSTimeInterval)interval

                                      target:(id)aTarget

                                    selector:(SEL)aSelector

                                    userInfo:(id)userInfo

                                     repeats:(BOOL)repeats {

    HLWeakTimerTarget* timerTarget = [[HLWeakTimerTargetalloc] init];

    timerTarget.target = aTarget;

    timerTarget.selector = aSelector;

//    通过这个方法把timer强引用的对象换为timerTarget

    timerTarget.timer = [NSTimerscheduledTimerWithTimeInterval:interval

                                                         target:timerTarget

                                                       selector:@selector(fire:)

                                                       userInfo:userInfo

                                                        repeats:repeats];

    return timerTarget.timer;

}


- (void) fire:(NSTimer *)timer {

    if(self.target) {

//        还是原来的target执行定时器的方法

        [self.targetperformSelector:self.selectorwithObject:nil];

    } else {

        [self.timerinvalidate];

    }

}


@end


使用:

 NSTimer *timer = [HLWeakTimerTargetscheduledTimerWithTimeInterval:1.0target:selfselector:@selector(timerFire:)userInfo:nilrepeats:YES];


-(void)timerFire:(id)userinfo {

    NSLog(@"Fire--------%@",userinfo);

}

1NSTimer 误差

http://blog.csdn.net/y_csdnblog_xx/article/details/51538247


加入到RunLoopmode方式,我们刚才的NSTimer默认添加在NSDefaultRunLoopMode上,而UIScrollView在滑动的时候,RunLoop会自动切换到 UITrackingRunLoopModeNSTimer并没有添加到这个RunLoop模式上,自然也是不会启动的。所以,如果我们想要NSTimerUIScrollView滑动的时候也会启动的话,只要将NSTimer添加NSRunLoopCommonModes上即可。NSRunLoopCommonModesRunLoop模式的集合。