【问题标题】:iOS - NSTimer causes to stop the app during animationiOS - NSTimer 导致在动画期间停止应用程序
【发布时间】:2014-04-15 06:59:18
【问题描述】:

在我的应用程序中,我使用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之间感到困惑,我应该怎么做?

【问题讨论】:

    标签: ios nstimer synchronous catransition


    【解决方案1】:

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

    考虑更改为像 SDWebImage 这样的异步图像管理库,它会在不阻塞主线程的情况下为您处理此问题(因此您的计时器或动画都不会受到影响)。

    【讨论】:

    • 非常感谢,你拯救了我的一天 :)
    • @wain...你能提供任何链接吗?对于异步图像管理,如果我只这样做 imgFeaturedEventImage.image = bannerObj.img_url;它显示警告“从 NSString 分配给 'UIImage *' 的不兼容指针类型”对不起,我完全是菜鸟。
    • 这个:github.com/rs/SDWebImage 可能是最流行的解决方案。向下滚动页面以获取示例代码。
    【解决方案2】:

    你可以试试:[NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:]

    NSThread : 在后台线程中运行

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-17
      • 1970-01-01
      • 2013-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多