NSMethodSignature& NSInvocation相当于swift 2

时间:2016-03-31 23:57:38

标签: ios swift nsinvocation

我如何在swift 2中写这个类? NSMethodSignature& NSInvocation在swift 2中不再存在

@implementation MyAuth

- (void)authorizeRequest:(NSMutableURLRequest *)request
                delegate:(id)delegate
       didFinishSelector:(SEL)sel {
    if (request) {
        NSString *value = [NSString stringWithFormat:@"%s %@", GTM_OAUTH2_BEARER, self.accessToken];
        [request setValue:value forHTTPHeaderField:@"Authorization"];
    }

    NSMethodSignature *sig = [delegate methodSignatureForSelector:sel];
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
    [invocation setSelector:sel];
    [invocation setTarget:delegate];
    [invocation setArgument:(__bridge void *)(self) atIndex:2];
    [invocation setArgument:&request atIndex:3];
    [invocation invoke];
}

- (void)authorizeRequest:(NSMutableURLRequest *)request
       completionHandler:(void (^)(NSError *error))handler {
    if (request) {
        NSString *value = [NSString stringWithFormat:@"%@ %@", @"Bearer", self.accessToken];
        [request setValue:value forHTTPHeaderField:@"Authorization"];
    }
}

提前感谢

1 个答案:

答案 0 :(得分:1)

Swift中没有

NSInvocation。但是,在这种情况下,NSInvocation实际上并不是必需的。我们从你设置参数的方式知道,你总是要调用一个带有两个参数对象指针类型的方法。 (假设您对索引2的意思是&self而不是self。)您可以使用performSelector:withObject:withObject:执行此操作。

[delegate performSelector:sel withObject:self withObject:request]

这可以在Swift 2中找到:

delegate?.performSelector(sel, withObject:self, withObject:request)

P.S。这真的很奇怪,因为看起来你有另一个版本的方法需要一个完成处理程序,这对Swift来说是完美的,除了正文似乎是不完整的,并且完成处理程序的类型不正确它不接受请求。