大佬教程收集整理的这篇文章主要介绍了ios – NSTimer类别阻止实现替换选择器,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
// NSTimer+Additions.h #import <Foundation/Foundation.h> typedef void (^VoidBlock)(); @interface NSTimer (NSTimer_Additions) + (NSTimer *)scheduleTimerWithTimeInterval:(NSTimeInterval)theseconds repeats:(BOOL)repeats actions:(VoidBlock)actions; @end #import "NSTimer+Additions.h" static VoidBlock _voidBlock; @interface NSTimer (AdditionsPrivatE) // Private stuff - (void)theBlock; @end @implementation NSTimer (NSTimer_Additions) + (NSTimer *)scheduleTimerWithTimeInterval:(NSTimeInterval)theseconds repeats:(BOOL)repeats actions:(VoidBlock)actions { [_voidBlock release]; _voidBlock = [actions copy]; NSTimer* timer = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:theseconds target:self SELEctor:@SELEctor(theBlock) userInfo:nil repeats:repeats]; [timer fire]; return [timer autorelease]; } - (void)theBlock { _voidBlock(); } @end
代码要点:https://gist.github.com/1065235
2011-07-05 14:35:47.068 TesteTimer [37716:903] *由于未捕获的异常’NSInvalidArgumentexception’终止应用程序,原因:'[NSTimer theBlock]:无法识别的选择器发送到类0x7fff70bb0a18′
我该如何使这个类别工作?
@interface NSTimer (AdditionsPrivatE) // Private stuff - (void)theBlock:(VoidBlock)voidBlock; @end @implementation NSTimer (NSTimer_Additions) + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)theseconds repeats:(BOOL)repeats actions:(VoidBlock)actions { NSInvocation * invocation = [NSInvocation invocationWithMethodSignature:[self instanceMethodSignatureForSELEctor:@SELEctor(theBlock:)]]; NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:theseconds invocation:invocation repeats:repeats]; [invocation setTarget:timer]; [invocation setSELEctor:@SELEctor(theBlock:)]; Block_copy(actions); [invocation setArgument:&actions aTindex:2]; Block_release(actions); return timer; } - (void)theBlock:(VoidBlock)voidBlock { voidBlock(); } @end
使用关联引用的问题是泄漏,因为释放块没有好处.
您可以使用associative references
将块附加到该特定NSTimer实例.
@implementation NSTimer (NSTimer_Additions) + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)theseconds repeats:(BOOL)repeats actions:(VoidBlock)actions { NSInvocation * invocation = [NSInvocation invocationWithMethodSignature:[self instanceMethodSignatureForSELEctor:@SELEctor(theBlock)]]; NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:theseconds invocation:invocation repeats:repeats]; [invocation setTarget:timer]; [invocation setSELEctor:@SELEctor(theBlock)]; objc_setAssociatedObject(timer,@"Block",actions,OBJC_ASSOCIATION_COPY); return timer; } - (void)theBlock { VoidBlock _voidBlock = (VoidBlock)objc_getAssociatedObject(self,@"Block"); _voidBlock(); } @end
以上是大佬教程为你收集整理的ios – NSTimer类别阻止实现替换选择器全部内容,希望文章能够帮你解决ios – NSTimer类别阻止实现替换选择器所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。