問題
1.定時(shí)器不準(zhǔn)問題
2.定時(shí)器內(nèi)存泄漏問題
答案
1.定時(shí)器不準(zhǔn)問題
1.當(dāng)我們使用NSTimer/CADisplayLink 的時(shí)候,會(huì)有不準(zhǔn)的時(shí)候,是由于當(dāng)時(shí)runloop 比較繁忙導(dǎo)致的.
2.NSTimer 停止計(jì)時(shí),是由于當(dāng)時(shí)的runloopModel 變?yōu)闈L動(dòng)模式導(dǎo)致的,要解決這個(gè)問題,我們需要把當(dāng)前的timer添加到 runloopModel 為 comment標(biāo)記的那個(gè)模式
2.NSTimer/CADisplayLink定時(shí)器內(nèi)存泄漏問題
方案1 通過自定義的第三方NSObject
這個(gè)會(huì)走消息發(fā)送,動(dòng)態(tài)解析,消息轉(zhuǎn)發(fā)
@interface FAN_Proxy : NSObject
+ (instancetype)proxyWithTarget:(id)target;
@property (weak, nonatomic) id target;
@end
@implementation FAN_Proxy
+ (instancetype)proxyWithTarget:(id)target
{
FAN_Proxy *proxy = [[FAN_Proxy alloc] init];
proxy.target = target;
return proxy;
}
- (id)forwardingTargetForSelector:(SEL)aSelector
{
return self.target;
}
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[FAN_Proxy proxyWithTarget:self] selector:@selector(timerTest) userInfo:nil repeats:YES];
@end
方案1 通過系統(tǒng)專門用來系統(tǒng)轉(zhuǎn)發(fā)的類 NSProxy解決問題
這個(gè)是專門用來做 消息轉(zhuǎn)發(fā)的,這個(gè)是最優(yōu)的解決方案
@interface FAN_Proxy : NSProxy
+ (instancetype)proxyWithTarget:(id)target;
@property (weak, nonatomic) id target;
@end
@implementation FAN_Proxy
+ (instancetype)proxyWithTarget:(id)target
{
// NSProxy對(duì)象不需要調(diào)用init抽莱,因?yàn)樗緛砭蜎]有init方法
MJProxy *proxy = [FAN_Proxy alloc];
proxy.target = target;
return proxy;
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
return [self.target methodSignatureForSelector:sel];
}
- (void)forwardInvocation:(NSInvocation *)invocation
{
[invocation invokeWithTarget:self.target];
}
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[FAN_Proxy proxyWithTarget:self] selector:@selector(timerTest) userInfo:nil repeats:YES];
@end