我如何在Swift 2中写这堂课? swift 2中不再存在NSMethodSignature和NSInvocation
@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"];
}
}
提前致谢
最佳答案
NSInvocation
在Swift中不可用。但是,在这种情况下,实际上不需要NSInvocation
。从设置参数的方式中我们知道,总是要使用两个参数对象指针类型来调用方法。 (假设索引2的意思是&self
而不是self
。)您可以使用performSelector:withObject:withObject:
做到这一点。
[delegate performSelector:sel withObject:self withObject:request]
这在Swift 2中可用:
delegate?.performSelector(sel, withObject:self, withObject:request)
附言这真的很奇怪,因为看来您有该方法的另一个版本需要一个完成处理程序,这对于Swift来说是完美的选择,除了正文似乎不完整,并且该完成处理程序的类型不合适之外,因为它不正确接受要求。
关于ios - Swift 2中的NSMethodSignature和NSInvocation等效项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36345815/