到现在已经有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]; }
我尝试将UILabel与数据以及正常的NSString一起发送。当我调用该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];
}
session:didReceiveData由Mulitipeer Connectivity Framework从专用线程调用。您正在尝试从此专用线程更新标签。不允许这样做,您应该只从主队列访问UI元素。解决方案是将更新标签的代码分派到主队列。
您可以在receiveTap:withLabelText中进行如下操作:
- (void)receivedTap:(NSString *)gesture withLabelText:(NSString *)labelText {
NSLog(@"%@", gesture);
NSLog(@"%@", labelText);
dispatch_async(dispatch_get_main_queue(), ^{
self.tapGestureLabel.text = labelText;
});
}
或在session:didReceiveData:fromPeer中处理它
dispatch_async(dispatch_get_main_queue(), ^{
[_gestureViewController receivedTap:gesture withLabelText:tapString];
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句