NSProxyを使用してtimerループ参照を防止

1121 ワード

.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");
}