gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:25:16 25 4
gpt4 key购买 nike

我有两种方法:

-(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/

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