ios 'NSInternalInconsistencyException',原因:'只在主线程上运行!' 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20597493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 22:46:56  来源:igfitidea点击:

'NSInternalInconsistencyException', reason: 'Only run on the main thread!' error

iosiphoneobjective-cmultithreadingcocoa-touch

提问by praks5432

So I know the reason for this error, but I'm not really sure how to get around it.

所以我知道这个错误的原因,但我不确定如何解决它。

I have a TextFieldthat I want to not be editable, but with scrolling enabled inside a view.

我有一个TextField我不想编辑的,但在视图中启用了滚动。

This is how I set up that view:

这就是我设置该视图的方式:

    - (void)tableView:(UITableView *) tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *component = self.resultsTuples[indexPath.row];
    NSString* serverUrl = @"http://staging.toovia.com";
    NSString* pageLink = component[@"$element"][@"ContactCard"][@"PageLink"];
    NSString* recUrl =[NSString stringWithFormat:@"%@%@&format=json&fields=summary&fields=session_info", serverUrl,pageLink];

    [AJAXUtils getAsyncJsonWithUrl:(NSURL *)[NSURL URLWithString:recUrl]  callback:^(NSDictionary *returnjson){
        if (returnjson != nil){
            NSLog(@"RETURN JSON : %@", returnjson);
            NSString *userPageLink = returnjson[@"Node"][@"SessionInfo"][@"PostingAs"][@"Key"];
            self.detailController.userPageLink = userPageLink;
            self.detailController.nodePage = returnjson[@"Node"][@"Key"];
            NSString *selectedCard = component[@"$element"][@"Title"];
         //   [self.detailController setDescription:component[@"element"][@"ContactCard"][@"Description"]];
            [self.detailController setPageTitle:selectedCard];
            NSString* photoUrl = component[@"$element"][@"ContactCard"][@"Cover"][@"Medium"][@"Link"];
            [self.detailController setRestaurantImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:photoUrl]]]];



            self.detailController.title = selectedCard;

            NSString* rating = component[@"$element"][@"Summary"][@"AverageRating"];
            self.detailController.rating =(NSInteger)rating;
            [self.navigationController pushViewController:self.detailController animated:YES];
        }
    }];

This is the viewWillAppearcode for the view:

这是viewWillAppear视图的代码:

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear: animated];
    self.rateView.notSelectedStar =[UIImage imageNamed:@"star-off.png"];
    self.rateView.fullSelectedStar = [UIImage imageNamed:@"star-on.png"];
    self.rateView.rating = self.rating;
    self.rateView.editable = YES;
    self.rateView.maxRating = 5;
    self.rateView.delegate = self;
    _pageTitleLabel.text = _pageTitle;
    _pageScoreLabel.text = _pageScore;
    _trendingImageView.image = [UIImage imageNamed:@"trending.png"];
    _restaurantImageView.image = _restaurantImage;

}

The full error is -

完整的错误是 -

    2013-12-16 01:22:50.362 ReviewApp[7332:441f] *** Assertion failure in void _UIPerformResizeOfTextViewForTextContainer(NSLayoutManager *, UIView<NSTextContainerView> *, NSTextContainer *, NSUInteger)(), /SourceCache/UIFoundation_Sim/UIFoundation-258.1/UIFoundation/TextSystem/NSLayoutManager_Private.m:1510
2013-12-16 01:22:50.365 ReviewApp[7332:441f] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Only run on the main thread!'

So I guess it's happening because the resizing of the text field (when content is set) has to happen on the main thread. How do I force this to happen/suppress this error? I'm not in control of the text field resizing am I?

所以我猜这是因为调整文本字段的大小(设置内容时)必须在主线程上发生。如何强制发生/抑制此错误?我无法控制文本字段的大小调整,是吗?

Thanks

谢谢

回答by David R?nnqvist

I'm guessing that the callback from AJAXUtilshappens on a background thread. I don't know if that is your code or not but you should do all UI operations (like setting text in a label, setting an image in an image view, pushing a view controller) on the main thread.

我猜测来自的回调AJAXUtils发生在后台线程上。我不知道这是否是您的代码,但您应该在主线程上执行所有 UI 操作(例如在标签中设置文本、在图像视图中设置图像、推送视图控制器)。

dispatch_sync(dispatch_get_main_queue(), ^{
    /* Do UI work here */
});

回答by iamlolz

Swift 3.0 version

斯威夫特 3.0 版本

DispatchQueue.main.async(execute: {
    /* Do UI work here */
})

回答by rmaddy

You must always perform UI code on the main thread. You are not, hence the error. Try this:

您必须始终在主线程上执行 UI 代码。你不是,因此错误。尝试这个:

[AJAXUtils getAsyncJsonWithUrl:(NSURL *)[NSURL URLWithString:recUrl]  callback:^(NSDictionary *returnjson){
    if (returnjson != nil){
        NSLog(@"RETURN JSON : %@", returnjson);
        NSString *userPageLink = returnjson[@"Node"][@"SessionInfo"][@"PostingAs"][@"Key"];
        self.detailController.userPageLink = userPageLink;
        self.detailController.nodePage = returnjson[@"Node"][@"Key"];
        NSString *selectedCard = component[@"$element"][@"Title"];
     //   [self.detailController setDescription:component[@"element"][@"ContactCard"][@"Description"]];
        [self.detailController setPageTitle:selectedCard];
        NSString* photoUrl = component[@"$element"][@"ContactCard"][@"Cover"][@"Medium"][@"Link"];
        [self.detailController setRestaurantImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:photoUrl]]]];

        self.detailController.title = selectedCard;

        NSString* rating = component[@"$element"][@"Summary"][@"AverageRating"];
        self.detailController.rating =(NSInteger)rating;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.navigationController pushViewController:self.detailController animated:YES];
        });
    }
}];

This ensures the display of the view controller is on the main thread. You may actually need to put a bit more of the code inside the call to dispatch_async.

这确保了视图控制器的显示在主线程上。您实际上可能需要在对dispatch_async.

回答by Manuel Escrig

Swift version

迅捷版

dispatch_async(dispatch_get_main_queue()){
      /* Do UI work here */
}

回答by Buhaescu Vlad

Also, it's not a very good way of doing things in didSelectRow. You should have a network layer, separate the network code from view controllers otherwise you will end up with huge view controller, code won't be testable.

此外,在 didSelectRow 中这不是一个很好的做事方式。你应该有一个网络层,将网络代码与视图控制器分开,否则你最终会得到巨大的视图控制器,代码将无法测试。