使用NSProxy防止timer循环引用

.h

@interface MyProxy : NSProxy

@property (nonatomic, weak) id object1;

- (id)initWithTarget:(id)tar1;

@end

.m

- (id)initWithTarget:(id)tar1{
    self.object1 = tar1;
    return self;
}

- (void)forwardInvocation:(NSInvocation *)invocation {

    if ([self.object1 respondsToSelector:invocation.selector]) {
        [invocation invokeWithTarget:self.object1];
    }
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
    NSMethodSignature *signature = [self.object1 methodSignatureForSelector:sel];
    return signature;
}

- (BOOL)respondsToSelector:(SEL)aSelector{
    return [self.object1 respondsToSelector:aSelector];
}

控制器中使用

    MyProxy *proxy = [[MyProxy alloc] initWithTarget:self];
    self.myTimer = [NSTimer timerWithTimeInterval:1 target:proxy selector:@selector(timerGo) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.myTimer forMode:NSRunLoopCommonModes];
    [self.myTimer fire];

- (void)dealloc {
    [self.myTimer invalidate];
    NSLog(@"HomeVC --- dealloc");
}

你可能感兴趣的:(使用NSProxy防止timer循环引用)