日々精進

新しく学んだことを書き留めていきます

指定秒後に引数付きでメソッドを呼び出す

NSInvocationを使うと引数も渡せる。
setArgumentで引数を渡す時になぜかメソッドの実引数を渡すとエラーになった。
ローカル変数に代入し直すと直った。なぜ。。

- (void)requestImageWithUrl:(NSURL *)url callback:(void (^)(NSImage *image))callback {
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image) {
        callback(image);
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
        DebugLog(@"request for %@ is failed. retry after %d second", request.URL.absoluteString, REQUEST_TO_SERVER_INTERVAL);

        SEL selector = @selector(requestImageWithUrl:callback:);
        NSMethodSignature *signature = [AdStore instanceMethodSignatureForSelector:selector];
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
        [invocation setSelector:selector];
        [invocation setTarget:self];
        NSURL *tempUrl = url;
        [invocation setArgument:&tempUrl atIndex:0];
        void (^tempCb)(NSImage *image) = callback;
        [invocation setArgument:&tempCb atIndex:1];

        [NSTimer scheduledTimerWithTimeInterval:REQUEST_TO_SERVER_INTERVAL invocation:invocation repeats:NO];
    }];
}

参考:objective c - How to pass an argument to a method called in a NSTimer - Stack Overflow