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

时间:2013-10-04 17:33:36

标签: 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

中执行此操作

1 个答案:

答案 0 :(得分:2)

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

来自documentation

  

- (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会导致死锁。

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