问题:使用block有什么好处?使用NSTimer写出一个使用b
2020-05-08 本文已影响0人
姜小舟
block的好处,最直接的就是代码紧凑,传值、回调都很方便,省去了写代理的很多代码。
对于这里根本没有必要使用block来刷新UILabel显示,因为都是直接赋值。
使用起来像这样:
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0
repeats:YES
callback:^() {
weakSelf.timeLabel.text = ...
}
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
再者,笔者认为这同时是在考验应聘者如何将NSTimer写成一个通用用的Block版本,因为上面NSTimer的带Block的方法是从iOS10之后才开始有的,而目前大多数App都是从iOS8就开始支持的,所以当遇到此提示可以讲一下如何自己封装一个带Block的NSTimer方法。以下为自定义带Block的Timer(OC和Swift):
OC自定义带Block的NSTimer:
//
// NSTimer+Block.m
//
#import "NSTimer+Block.h"
@implementation NSTimer (Block)
+ (NSTimer *)block_scheduledTimerWithTimeInterval:(NSTimeInterval)inTimeInterval block:(void (^)())inBlock repeats:(BOOL)inRepeats
{
void (^block)() = [inBlock copy];
NSTimer * timer = [self scheduledTimerWithTimeInterval:inTimeInterval target:self selector:@selector(__executeTimerBlock:) userInfo:block repeats:inRepeats];
return timer;
}
+ (NSTimer *)block_timerWithTimeInterval:(NSTimeInterval)inTimeInterval block:(void (^)())inBlock repeats:(BOOL)inRepeats
{
void (^block)() = [inBlock copy];
NSTimer * timer = [self timerWithTimeInterval:inTimeInterval target:self selector:@selector(executeTimerBlock:) userInfo:block repeats:inRepeats];
return timer;
}
+ (void)executeTimerBlock:(NSTimer *)inTimer;
{
if([inTimer userInfo])
{
void (^block)() = (void (^)())[inTimer userInfo];
block();
}
}
@end
Swift自定义带Block的Timer:
import Foundation
import UIKit
extension Timer {
/**
将来从iOS 10.0开始支持后可以用系统提供的方法:
open class func scheduledTimer(withTimeInterval interval: TimeInterval, repeats: Bool, block: @escaping (Timer) -> Swift.Void) -> Timer
由于系统提供的block方法是从iOS 10.0,所以下方是自己写的带block的Timer
由此方法创建的Timer可以在deinit方法中调用invalidate注销
deinit {
myTimer.invalidate()
}
*/
open class func block_scheduledTimer(timeInterval ti: TimeInterval, repeats yesOrNo: Bool, timerBlock: @escaping (Timer) -> Swift.Void) -> Timer {
let timer = Timer.scheduledTimer(timeInterval: ti, target: self, selector: #selector(block_timerSelector), userInfo: timerBlock, repeats: yesOrNo)
return timer
}
@objc private class func block_timerSelector(timer : Timer) -> Void {
guard let tBlock = timer.userInfo as? (Timer) -> Swift.Void else { return }
tBlock(timer);
}
}