gpt4 book ai didi

ios - 执行选择器警告 vs dispatch _async

转载 作者:行者123 更新时间:2023-11-28 17:56:55 24 4
gpt4 key购买 nike

[不重复:仔细阅读问题和已经给出的答案,我已经阅读了它们]

我正面临这个问题,我需要替换 -performSelector 方法,因为它会在带有 ARC 的编译器中引起警告

performSelector may cause a leak because its selector is unknown

我知道关于那个主题有不同的问题:

而且我也知道避免该警告的技术。
有时作为一种解决方案,我发现最推荐的建议是使用 dispatch_async(dispatch_get_main_queue(),^(void) { WHATEVER });但据我所知,调度需要在下一个运行循环中执行 block ,-performSelector(没有延迟)会立即执行。
为什么会有这种心理自慰?想象一下,您正在使用新的 Gamekit 方法进行身份验证,游戏套件可以在 auth block 内向您发送一个 View Controller ,让用户执行一些操作(例如创建 id、登录等)。如果他/她想要查看该 View Controller ,警告用户可能很有用。为了做到这一点和其他事情,我正在编写一个协议(protocol)。特别是该方法应返回 BOOL - (BOOL)shouldLoadGameKitViewController: (UIViewController*) viewController;,我想使用 -performSelector 调用它。这就是重点,如果方法没有立即返回,我就无法从委托(delegate)中得到答案。
我正在使用 NSInvocation 来实现这一点但是很冗长,是否存在其他方式?

[使用代码更新]
请注意,现在我正在使用调用,线程检查部分仍未实现。评论了给出警告的部分

- (void) dispatchToDelegate: (SEL) selector withArg: (id) arg error: (NSError*) err
{
NSMethodSignature *methodSig = [[self class] instanceMethodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSig];
[invocation setTarget:self.delegate];
if([self.delegate respondsToSelector: selector])
{
if(arg != NULL) {
[invocation setArgument:&arg atIndex:2];
[invocation setArgument:&err atIndex:3];

// [_delegate performSelector: selector withObject: arg withObject: err];

}else {
[invocation setArgument:&err atIndex:2];
// [_delegate performSelector: selector withObject: err];

}
[invocation invoke];

}
else
DLog(@"Method not implemented in the delegate");
}

[某种尚未测试的解决方案]

- (BOOL) dispatchToDelegate: (SEL) selector withArg: (id) arg error: (NSError*) err
{
NSMethodSignature *methodSig = [[self class] instanceMethodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSig];
[invocation setTarget:self.delegate];
BOOL result = NO;
if([self.delegate respondsToSelector: selector])
{
if(arg != NULL) {
[invocation setArgument:&arg atIndex:2];
[invocation setArgument:&err atIndex:3];

// [_delegate performSelector: selector withObject: arg withObject: err];

}else {
[invocation setArgument:&err atIndex:2];
// [_delegate performSelector: selector withObject: err];

}
if ([NSThread isMainThread]) {
[invocation invoke];
}
else{
[invocation performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:YES];
}
[invocation getReturnValue:&result];
}
else
NSLog(@"Missed Method");
return result;
}

使用 NSMethodSignature 方法,可以准备好并请求返回类型。我仍然没有测试,但它应该可以解决问题。

最佳答案

尝试这样做以避免泄漏或“未知选择器发送到实例”问题:

SEL selector = NSSelectorFromString(@"methodName::");
if ([obj respondsToSelector:selector])
[obj performSelector:selector withObject@[args,array]];

关于ios - 执行选择器警告 vs dispatch _async,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16898702/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com