iOS - NSTimer导致在动画期间停止应用程序

时间:2014-04-15 06:59:18

标签: ios nstimer synchronous catransition

在我的应用中,我使用CATransition来滑动横幅视图。我的代码是这样的:

viewDidLoad中()

- (void)viewDidLoad
{
    [super viewDidLoad];
    bannerList = [[NSMutableArray alloc] init];
    bannerList = [WebFunctions fetchBannerDataHavingUrl:@"banners/event"];

    NSTimer* timer = [NSTimer timerWithTimeInterval:3.0f target:self selector:@selector(updateLabel) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}

updateLabel

- (void)updateLabel {

    BannerDC *bannerObj = [[BannerDC alloc] init];
    if (count == bannerList.count){
        count = 0;
    } else {
        bannerObj = [bannerList objectAtIndex:count];

        lblFeaturedEventTitle.text = bannerObj.line1;
        imgFeaturedEventImage.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:bannerObj.img_url]]];

        // get the view that's currently showing
        [self.viewBannersBackground removeFromSuperview];
        [self.viewBanners addSubview:self.viewBannersBackground];

        // set up an animation for the transition between the views
        CATransition *animation = [CATransition animation];
        [animation setDuration:1.0];
        [animation setType:kCATransitionPush];
        [animation setSubtype:kCATransitionFromRight];
        [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];

        [[self.viewBannersBackground layer] addAnimation:animation forKey:@"SwitchToView1"];

        count++;
    }
}

因此,由于计时器功能,我的主线程在动画期间卡住(或显示延迟)。我想在线程中使用这个动画,我在NSThreadNSTimer之间感到困惑,我该怎么做呢?

2 个答案:

答案 0 :(得分:1)

您不应该使用dataWithContentsOfURL:[下载横幅图片,因为它是同步的,您之前可能已经下载了该图片并可以重复使用。

查看更改为SDWebImage之类的异步图像管理库,它将为您处理此问题而不会阻塞主线程(因此您的计时器或动画都不会受到影响)。

答案 1 :(得分:0)

您可以尝试:[NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:重复:]

NSThread:在后台线程中运行

NSTimer(应该在主线程中调用):在主线程中运行