postNotificationName同步调用导致的白屏问题

项目的聊天窗口遇到一个白屏的问题:

只要发送一个图片后,,再发任何消息都导致聊天窗口白屏。

出问题的代码摘要如下:

//HWChatViewController.m- (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadChatCollectionViewData) name:HWCHAT_VIEW_NEED_RELOAD object:nil];}-(void)reloadChatCollectionViewData { HWLog(@"111111*********"); yoho_dispatch_execute_in_main_queue(^{ HWLog(@"22222=========="); [_collectionView reloadData]; [_collectionView layoutIfNeeded]; HWLog(@"33333+++++++++++"); [_collectionView scrollToBottomAnimated:YES]; });}

//HWChatManager.m-(void)reloadChatCollectionViewData { yoho_dispatch_execute_in_main_queue(^{ HWLog(@"抛通知HWCHAT_VIEW_NEED_RELOAD"); [[NSNotificationCenter defaultCenter] postNotificationName:HWCHAT_VIEW_NEED_RELOAD object:nil]; });}

//HWPhotoMediaItem- (UIView *)mediaView { if (_cachedImageView == nil) { CGSize size = [self mediaViewDisplaySize]; UIImageView *imageView = [[UIImageView alloc] init]; NSURL *url = [NSURL URLWithString:_imageUrl]; if ([[url.scheme lowercaseString] isEqualToString:@"http"]) { [imageView sd_setImageWithURL:url completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { _size = image.size; yoho_dispatch_execute_in_main_queue(^{ HWLog(@"抛通知HWCHAT_VIEW_NEED_RELOAD"); [[NSNotificationCenter defaultCenter] postNotificationName:HWCHAT_VIEW_NEED_RELOAD object:nil]; }); }]; } else { //other code } //other code } return _cachedImageView;}

聊天窗口发图,输出的log如下:

|[HWChatManager.m 175]: __45-[HWChatManager reloadChatCollectionViewData]_block_invoke 抛通知HWCHAT_VIEW_NEED_RELOAD|[HWChatViewController.m 162]: -[HWChatViewController reloadChatCollectionViewData] 111111*********|[HWChatViewController.m 164]: __52-[HWChatViewController reloadChatCollectionViewData]_block_invoke 22222==========|[HWPhotoMediaItem.m 41]: __29-[HWPhotoMediaItem mediaView]_block_invoke_2 抛通知HWCHAT_VIEW_NEED_RELOAD|[HWChatViewController.m 162]: -[HWChatViewController reloadChatCollectionViewData] 111111*********|[HWChatViewController.m 164]: __52-[HWChatViewController reloadChatCollectionViewData]_block_invoke 22222==========|[HWChatViewController.m 167]: __52-[HWChatViewController reloadChatCollectionViewData]_block_invoke 33333+++++++++++|[HWChatViewController.m 167]: __52-[HWChatViewController reloadChatCollectionViewData]_block_invoke 33333+

从log可以看出HWChatManager抛通知HWCHAT_VIEW_NEED_RELOAD使得[HWChatViewController reloadChatCollectionViewData]被调用。

[_collectionView reloadData];因为要绘制HWPhotoMediaItem,if(_cachedImageView == nil)时又抛了一个同样的通知,再次同步调用了[HWChatViewController reloadChatCollectionViewData]。

于是[_collectionView reloadData];未完成的情况下又reloadData了一次,图片是发出去且正常显示了,但导致了界面绘制错乱,后续发消息都白屏了(为什么reloadData过程中再reloadData会错乱导致白屏,这个问题待研究).

避免错乱的解决办法是mediaView里抛通知时在异步线程抛,利用线程切换避免reloadData过程中再reloadData。

我只愿,在你的理想和希望里能为你增加一点鼓励,

postNotificationName同步调用导致的白屏问题

相关文章:

你感兴趣的文章:

标签云: