iOS面试题与核心基础之定时器

2022-03-23  本文已影响0人  十拿九稳啦

常用的就这三种


NSTimer 和 CADisplayLink被添加到RunLoop之后还有两个坑。

关于invalidate方法的官解阐释
Stops the receiver from ever firing again and requests its removal from its run loop
This method is the only way to remove a timer from an NSRunLoop object

如果你要适配低版本,还有个中间代理弱引用的方式。
直接看代码

#import <Foundation/Foundation.h>

@interface ALProxy : NSObject
+ (instancetype)proxyWithTarget:(id)target;
@property (weak, nonatomic) id target;
@end

@implementation ALProxy

+ (instancetype)proxyWithTarget:(id)target
{
    MJProxy *proxy = [[MJProxy alloc] init];
    proxy.target = target;
    return proxy;
}

- (id)forwardingTargetForSelector:(SEL)aSelector
{
    return self.target;
}

@end

self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[ALProxy proxyWithTarget:self] selector:@selector(timerTest) userInfo:nil repeats:YES];


定时器都有后台不执行的问题

解决方案也得看业务的具体需求

如果你是个懒人,想复制粘贴就解决以上问题,还想多个定时器并存,那给你吧

希望你读完了,发现哪里有问题能反馈一下
啥? 不会Swift?那无能为力了,这都swift 5+ 了

/// 全局定时器
class TimerManager {
    /// 定时器缓存
    private var timers: [String: Any] = [:]
    /// 定时器key缓存
    private var timerKeyCache: [String] = []

    /// 因为涉及到多线程同时读写,为了避免出现错误,执行数据变更时需要加锁操作
    private let semaphore = DispatchSemaphore(value: 1)

    static let shared = TimerManager()

    /// 定时器
    /// - Parameters:
    ///   - timerKey: 定时器唯一key
    ///   - target: target
    ///   - selector: Selector 要执行的方法
    ///   - start: DispatchTime 开始时间
    ///   - interval: TimeInterval 延时时长 默认1s
    ///   - repeats: 是否重复
    ///   - async: 是否异步
    /// - Returns: 是否开启定时器成功
    func schedule(timerKey: String, target: NSObject, selector: Selector, start: DispatchTime = .now(), interval: TimeInterval = 1, repeats: Bool = true, async: Bool = true) -> Bool {
        guard !timerKey.isEmpty || start.rawValue <= 0 || interval <= 0 else {
            return false
        }

        if timerKeyCache.contains(timerKey) {
            return false
        }

        let timerQueue = async ? DispatchQueue.global() : DispatchQueue.main
        let timer = DispatchSource.makeTimerSource(queue: timerQueue)
        semaphore.wait()
        timers[timerKey] = timer
        timerKeyCache.append(timerKey)
        semaphore.signal()
        timer.schedule(deadline: start, repeating: interval)
        timer.setEventHandler { [weak self] in
            if target.responds(to: selector) {
                target.perform(selector)
            }
            if !repeats {
                _ = self?.cancelTimer(forKey: timerKey)
            }
        }
        timer.resume()
        return true
    }

    /// 取消定时器
    /// - Parameter timerKey: 定时器唯一key
    /// - Returns: 是否关闭成功
    func cancelTimer(forKey key: String) -> Bool {
        guard !key.isEmpty else {
            return false
        }

        guard let timer = timers[key] as? DispatchSourceTimer else {
            return false
        }

        timer.cancel()
        semaphore.wait()
        if let index = timerKeyCache.firstIndex(of: key) {
            timerKeyCache.remove(at: index)
        }

        timers.removeValue(forKey: key)
        semaphore.signal()
        return true
    }
}

面试题

  1. iOS 为什么把NSTimer对象以NSDefaultRunLoopMode(kCFRunLoopDefaultMode)添加到主运行循环以后,滑动scrollview的时候NSTimer却不动了?

主线程的 RunLoop 里有两个预置的 Mode:kCFRunLoopDefaultMode 和 UITrackingRunLoopMode。这两个 Mode 都已经被标记为”Common”属性。DefaultMode 是 App 平时所处的状态,TrackingRunLoopMode 是追踪 ScrollView 滑动时的状态。当你创建一个 Timer 并加到 DefaultMode 时,Timer 会得到重复回调,但此时滑动一个TableView时,RunLoop 会将 mode 切换为 TrackingRunLoopMode,这时 Timer 就不会被回调,并且也不会影响到滑动操作

  1. 定时器切到后台就不走了,如何解决这个问题?
上一篇 下一篇

猜你喜欢

热点阅读