一、引言
在iOS7之前,系統(tǒng)一直沒(méi)有提供一個(gè)完整的框架來(lái)描述任務(wù)進(jìn)度相關(guān)的功能。這使得在開(kāi)發(fā)中進(jìn)行耗時(shí)任務(wù)進(jìn)度的監(jiān)聽(tīng)將什么麻煩,在iOS7之后,系統(tǒng)提供了NSProgress類來(lái)專門(mén)報(bào)告任務(wù)進(jìn)度。
二、創(chuàng)建單任務(wù)進(jìn)度監(jiān)聽(tīng)器
單任務(wù)進(jìn)度的監(jiān)聽(tīng)是NSProgress最簡(jiǎn)單的一種運(yùn)用場(chǎng)景,我們來(lái)用定時(shí)器模擬一個(gè)耗時(shí)任務(wù),示例代碼如下:
@interface ViewController ()
{
NSProgress * progress;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//這個(gè)方法將創(chuàng)建任務(wù)進(jìn)度管理對(duì)象 UnitCount是一個(gè)基于UI上的完整任務(wù)的單元數(shù)
progress = [NSProgress progressWithTotalUnitCount:10];
NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(task) userInfo:nil repeats:YES];
//對(duì)任務(wù)進(jìn)度對(duì)象的完成比例進(jìn)行監(jiān)聽(tīng)
[progress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"進(jìn)度= %f",progress.fractionCompleted);
}
-(void)task{
//完成任務(wù)單元數(shù)+1
if (progress.completedUnitCount