现在已经有4天了,我一直在尝试更改属于在多重连接会话中连接的对等方的视图的视图或元素。会话已创建,我可以连接两个设备并在两者之间发送数据,但每当我尝试更改标签时都没有任何反应。当我使用NSLog
查看label.text
是什么时,它会返回null。
以下是我的会话didReceiveData:
方法:
- (void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID {
NSLog(@"did receive data, %@", peerID.displayName);
NSDictionary *dict = @{
@"data": data,
@"peerID": peerID
};
[[NSNotificationCenter defaultCenter] postNotificationName:@"MCDidReveiveDataNotification" object:nil userInfo:dict];
NSArray *arrayFromData = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSString *gesture = [arrayFromData objectAtIndex:0];
UILabel *tapLabel = [arrayFromData objectAtIndex:1];
NSString *tapString = tapLabel.text;
[_gestureViewController receivedTap:gesture withLabelText:tapString]; }
我尝试使用数据和普通的NSString发送UILabel。当我调用gestureViewController
方法时,
receivedTap:gesture withLabelText:tapString
我能够NSLog
标签文本,但是当我尝试将当前viewController的tapGestureLabel
设置为tapString
文本时,没有任何反应。
这是我的receivedTap:gesture withLabelText:tapString
方法:
- (void)receivedTap:(NSString *)gesture withLabelText:(NSString *)labelText {
NSLog(@"%@", gesture);
NSLog(@"%@", labelText);
self.tapGestureLabel.text = labelText; }
我调派主线程的想法:
- (void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID {
NSDictionary *dict = @{
@"data": data,
@"peerID": peerID
};
[[NSNotificationCenter defaultCenter] postNotificationName:@"MCDidReceiveDataNotification" object:nil userInfo:dict];
NSArray *arrayFromData = [NSKeyedUnarchiver unarchiveObjectWithData:data];
UIImage *image = [arrayFromData objectAtIndex:2];
[self performSelectorOnMainThread:@selector(changeImage:) withObject:image waitUntilDone:NO];
}
我的changeImage:选择器方法:
- (void)changeImage:(UIImage *)image {
[_gestureViewController.imageView setImage:image];
}
答案 0 :(得分:0)
session:Mulifipeer连接框架从专用线程调用didReceiveData。您正在尝试从此专用线程更新标签。这是不允许的,您应该只访问主队列中的UI元素。解决方案是将更新标签的代码段发送到主队列。
您可以在receivedTap:withLabelText中执行以下操作:
- (void)receivedTap:(NSString *)gesture withLabelText:(NSString *)labelText {
NSLog(@"%@", gesture);
NSLog(@"%@", labelText);
dispatch_async(dispatch_get_main_queue(), ^{
self.tapGestureLabel.text = labelText;
});
}
或者在会话早期处理它:didReceiveData:fromPeer
dispatch_async(dispatch_get_main_queue(), ^{
[_gestureViewController receivedTap:gesture withLabelText:tapString];
});