0

这是我有的两种方法:

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

4

1 回答 1

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

文档中:

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

...

arg
调用方法时传递给方法的参数。nil如果方法不带参数,则通过。


或者

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

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

关于这两种方法之间细微差别的一些见解可以在这里找到:主队列上的 performSelectorOnMainThread 和 dispatch_async 有什么区别?

于 2013-10-04T17:35:39.827 回答