UIActivityIndi​​catorView 不会停止 [英] UIActivityIndicatorView won't stop

查看:62
本文介绍了UIActivityIndi​​catorView 不会停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 iOS 中进行一些 JSON 解析,我想添加一个微调器,这很好用,但我无法停止微调器,我想了解原因.

I'm playing with some JSON parsing in iOS and i wanted to add a spinner, this works wel but i can't stop the spinner and i would like to understand why.

[spinner stopAnimating] 在异步块中被调用,我相信这就是问题所在,也许是因为我无法在块中调用微调器上的方法?我已经记录了 Spinner obj,输出是:

[spinner stopAnimating] is called in the async block and i believe thats where the problem is, maybe because i can't call the method on spinner in the block? i've logged the spinner obj and the output is:

<UIActivityIndicatorView: 0x76905f0; frame = (150 230; 20 20); layer = <CALayer: 0x768ffb0>>

也许有人能让我了解如何在 Objective-c 中处理这种异步方法.我绝对是初学者.

Maybe somebody can make me understand how to deal with this async methods in objective-c. I'm a absolute beginner.

代码:

- (void)viewDidLoad{
  [super viewDidLoad];

  UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  spinner.center = CGPointMake(160, 240);
  [self.view addSubview:spinner];
  [spinner startAnimating];


  dispatch_async(kBgQueue, ^{

    NSData* data = [NSData dataWithContentsOfURL:
                    kLatestKivaLoansURL];
    [self performSelectorOnMainThread:@selector(fetchedData:)
                           withObject:data waitUntilDone:YES];
     NSLog(@"loans: %@", spinner);
     [spinner stopAnimating];
  });


}

推荐答案

Never never never (never!) 在后台线程上与界面交谈.您想要的是跳回主线程 - 正如您正确怀疑的那样.很简单:

Never never never (never!) talk to the interface on a background thread. What you want is to jump back into the main thread - as you rightly suspect. It's easy-peasy:

[spinner startAnimating];
dispatch_async(kBgQueue, ^{
    NSData* data = [NSData dataWithContentsOfURL:
                    kLatestKivaLoansURL];
    // ... do other stuff in the background
    dispatch_async(dispatch_get_main_queue(), ^{
        [spinner stopAnimating];
    });
});

但是,您将 performSelectorOnMainThread:withObject:waitUntilDone:waitUntilDone:YES 一起使用也是错误的(或者至少是一种非常糟糕的气味),因为您不应该阻塞在你的后台线程上.只需在后台线程上调用一个方法(除非它触及界面),当结果返回时,它就会返回.

However, your use of performSelectorOnMainThread:withObject:waitUntilDone: with waitUntilDone:YES is also wrong (or at least a very bad smell), since you should not be blocking on your background thread. Just call a method right here on the background thread (unless it touches the interface) and when the result comes back, it comes back.

这篇关于UIActivityIndi​​catorView 不会停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆