Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS

Vanessa Cantero Gómez
Vanessa Cantero Gómez
7,376 Points

Improving the animation task in Crystal Ball App

Hi guys, I have written a better way to load the images.

If you have already made the Animating and Intercepting Events of Cristal Ball App, you saw that you had to write all images names by yourself in viewDidLoad method.

Well, I thought, there's a better (faster) way to do this because all images have a common name: "CB000". So I write this method:

- (void) loadAllBackgroundImages {
    NSString *cbName = @"CB000";
    NSString * imageName;
    NSMutableArray *arrayWithUIImages = [[NSMutableArray alloc] init];

    for (int i = 1; i <61 ; i++) {
        if (i < 10) {
            imageName = [cbName stringByAppendingFormat:@"0%d",i];
        } else {
            imageName = [cbName stringByAppendingFormat:@"%d",i];
        }

        [arrayWithUIImages addObject:[UIImage imageNamed:imageName]];
    }
    self.backgroundImageView.animationImages = arrayWithUIImages;
    self.backgroundImageView.animationDuration = 2.5f;
    self.backgroundImageView.animationRepeatCount = 1;
}

Then, in viewDidLoad you just have to write

[self loadAllBackgroundImages];

Hope you like it! And If you want to do better (I'm a newbie in objective-c) don't hesitate to do it so I can learn too!

EDIT: Hey, the markdown doesn't work, so I hope you can understand the code! :)

1 Answer

Here's a little trick to pad a positive integer with zeros in front to make it 4-digit long (e.g. 0001, 0032, 0150, 9999):

[NSString stringWithFormat:@"%04d",i];

The formatting string of course works with all other methods/functions including NSLog and stringByAppendingFormat etc.