1、弱應用
__weak typeof(self) weakSelf = self;
__strong typeof(self) strongSelf = weakSelf;
2、NSTimer
方法一:
#import <objc/runtime.h>
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) id target;
_target = [NSObject new];
class_addMethod([_target class], @selector(test), class_getMethodImplementation([self class], @selector(test)), "v@:");
_timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:_target selector:@selector(test) userInfo:nil repeats:YES];
- (void)test{
NSLog(@"test");
}
-(void)dealloc{
NSLog(@"dealloc");
[_timer invalidate];
_timer = nil;
}
方法二:
-(void)didMoveToParentViewController:(UIViewController *)parent
{
if (!parent) {
[_timer invalidate];
_timer = nil;
}
}
方法三:
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface TestProxy : NSProxy
@property (nonatomic, weak) id target;
@end
NS_ASSUME_NONNULL_END
#import "TestProxy.h"
@implementation TestProxy
-(NSMethodSignature *)methodSignatureForSelector:(SEL)sel{
return [self.target methodSignatureForSelector:sel];
}
-(void)forwardInvocation:(NSInvocation *)invocation{
[invocation invokeWithTarget:self.target];
}
@end
@property (nonatomic, strong) TestProxy *testProxy;
_testProxy = [TestProxy alloc];
_testProxy.target = self;
_timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:_testProxy selector:@selector(test) userInfo:nil repeats:YES];
方法四:
#import <Foundation/Foundation.h>
@interface NSTimer (JNTimer)
+ (NSTimer *)jn_scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(void))block;
@end
#import "NSTimer+JNTimer.h"
@implementation NSTimer (JNTimer)
+ (NSTimer *)jn_scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(void))block{
return [self scheduledTimerWithTimeInterval:interval target:self selector:@selector(jn_blockHandle:) userInfo:block repeats:YES];
}
+ (void)jn_blockHandle:(NSTimer *)timer{
void(^block)(void) = timer.userInfo;
if (block) {
block();
}
}
@end
__weak typeof(self) weakSelf = self;
_timer = [NSTimer jn_scheduledTimerWithTimeInterval:1.0 repeats:YES block:^{
__strong typeof(self) strongSelf = weakSelf;
[strongSelf test];
}];
Demo:https://github.com/JnKindle/PerformanceOptimization-NSTimer
歡迎大家訪問我的GitHub
GitTub:https://github.com/JnKindle