iPhone SDKレシピ3:UIProgressViewの使い方

ポイント

UIProgressViewのprogressプロパティは、ある処理をしているスレッド中で変更しても、その処理が終了するまで画面に反映されない。
そこで、performSelectorInBackground:withObject:メソッドを利用して、バックグラウンドでprogressプロパティを変更する。

ソース

// tmpViewController.h
#import <UIKit/UIKit.h>

@interface tmpViewController : UIViewController {
	IBOutlet UIProgressView *progressBar;
}

@property(nonatomic, retain) IBOutlet UIProgressView *progressBar;

- (IBAction)start;
- (void) progress:(NSNumber *)amount;

@end


// tmpViewController.m
#import "tmpViewController.h"

@implementation tmpViewController
@synthesize progressBar;

- (IBAction)start {
	progressBar.progress = 0;
	for (int i=0; i<100; i++) {
		[self performSelectorInBackground:@selector(progress:) withObject:[NSNumber numberWithFloat:0.01f]];
		[NSThread sleepForTimeInterval:0.1f];
	}
}

// バックグラウンドでprogressを変更
- (void)progress:(NSNumber *)amount {
	progressBar.progress += [amount floatValue];
}

- (void)dealloc {
	[progressBar release];
    [super dealloc];
}

@end