views:

61

answers:

4

i want to have a background thread in my app that changes an image every 5 seconds for as long as the app is being run. Can someone point me in the direction of how this works? I am new to threads.

A: 

You do not need a thread for that. You can do it with a timer which is simpler than a thread. See the timer programming guide.

Jaanus
A: 

You can use an NSTimer for this. No need to spawn off e new thread:

[NSTimer scheduledTimerWithTimeInterval:5.0s target:self selector:@selector(updateImage) userInfo:nil repeats:YES];

Claus Broch
wow that sounds really simple. When doing this though, can the user still interact with the app normally?
Brodie
Yes, the timer will just hook up to the runloop that services the user interactions. Whenever the timer fires, it will just get a slot in the event handling.If the image switching requires some lengthy processing you might however need to spawn off a thread for doing it. But that can easily be initiated from the timer callback.
Claus Broch
+1  A: 

If you are using UIImageView and want an animated change between images you do not even need a timer. UIImageView can animate between images all by itself:

NSArray *images = [NSArray arrayWithObjects: [UIImage imageNamed: @"foo.png"],
                                             [UIImage imageNamed: @"bar.png"],
                                             nil];

yourImageView.animationImages = images;
yourImageView.animationDuration = 5.0s;
[yourImageView startAnimating];

The details are documented in the UIImageView docs.

toto
+1  A: 

An NSTimer will probably do what you are looking to do, however, calls from NSTimer will normally block the main thread, if the process is involved, or you need to getting something from the internets to switch out the picture, you will need to create a new thread to do this.

For information on threading, I highly recommend the CS193P Lecture on performance, They go into detail on NSThread, NSOperations, ect.

Also, from apple, Threading programing Guide.

Ben