ios - 使用 performSelectorOnMainThread 将变量传递给其他方法

标签 ios objective-c

我有两种方法:

-(void)session:(MCSession *)session didStartReceivingResourceWithName:(NSString   *)resourceName fromPeer:(MCPeerID *)peerID withProgress:(NSProgress *)progress

{
NSLog(@"RECEIVING... %@ from peer: %@", progress, peerID);
[self performSelectorOnMainThread:@selector(updateUIWithPeerId:) withObject:nil waitUntilDone:YES];
}

- (void) updateUIWithPeerId:(MCPeerID *)peerID {

UIProgressView *progressBar = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
progressBar.frame = CGRectMake(0, 200, 100, 20);
progressBar.progress = 0.5;
//UIButton* btn = [BluetoothDeviceDictionary objectForKey:peerID];
[self.view addSubview:progressBar];

UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"Alert View Title" message:@"Alert View Text" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
[alertView show];
}

第一个使用以下代码调用第二个:

[self performSelectorOnMainThread:@selector(updateUIWithPeerId:) withObject:nil waitUntilDone:YES];

但我想将此变量传递给第二个方法:peerID。通常我会这样做:

[self updateUIWithPeerId: peerID];

但我不能在 performSelectorOnMainThread 中执行此操作

最佳答案

[self performSelectorOnMainThread:@selector(updateUIWithPeerId:)
                       withObject:peerID
                    waitUntilDone:YES];

来自documentation :

- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thread withObject:(id)arg waitUntilDone:(BOOL)wait

...

arg
The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.


或者

dispatch_sync(dispatch_get_main_queue(), ^{
    [self updateUIWithPeerId:peerID];
}

但绝对不要从主队列调用它,因为在当前队列上调用 dispatch_sync 会导致死锁。

关于这两种方法之间的细微差别的一些见解可以在这里找到:Whats the difference between performSelectorOnMainThread and dispatch_async on main queue?

关于ios - 使用 performSelectorOnMainThread 将变量传递给其他方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19187407/

相关文章:

objective-c - 检索所有已安装的 macOS 服务的列表?

iphone - NSDateComponents 格式问题

iOS 8 TestFlight 不安装应用程序

c++ - 如何让小球朝某个方向移动?

ios - 当单元格不可见时,UITableView indexPathForCell 返回 null

ios - Firebase 登录的授权错误列表

objective-c - Finder 脚本桥接关闭

ios - 检测 applicationWillEnterForeground 中存在哪个 View

ios - 查明是否没有进行任何接触?

iphone - 如何更改 UINavigationBar 中的 UIBarButtonItem