Question

In my app I am using CATransition to slide a banner view. My code is something like this:

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];
}

And 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++;
    }
}

so, due to the timer function my main thread gets stuck (or shows a delay) during animation. I want to use this animation in thread, and I am confused between NSThread and NSTimer, how should I be doing this?

Was it helpful?

Solution

You shouldn't be using dataWithContentsOfURL:[ to download your banner image because it is synchronous and you may have already downloaded the image previously and could reuse it.

Look at changing to an asynchronous image management library like SDWebImage which will handle this for you without blocking the main thread (so neither your timer or animation will be affected).

OTHER TIPS

You can try: [NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:]

NSThread : run in background thread

NSTimer (should call in main thread) : run in main thread

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top