我在看Sam的自學iPhone開發,我不明白爲背景提供的示例。非backgrounding代碼:如何使用beginBackgrounTaskWithExpirationHandler選擇性地指定要在後臺執行的操作:
- (void)viewDidLoad {
[super viewDidLoad];
count=0;
theTimer=[NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(countUp)
userInfo:nil
repeats:YES];
}
而且backgrounding版本是:
- (void)viewDidLoad {
[super viewDidLoad];
counterTask = [[UIApplication sharedApplication]
beginBackgroundTaskWithExpirationHandler:^{
// If you're worried about exceeding 10 minutes, handle it here
}];
count=0;
theTimer=[NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(countUp)
userInfo:nil
repeats:YES];
}
我不明白的是,其中的關聯是活動之間的背景和beginBackgroundTaskWithExpirationHandler進行。
在這個例子中的的NSTimer是在後臺運行 - 但如果有一些其他的活動,在後臺執行,以及即假設代碼:
- (void)viewDidLoad {
[super viewDidLoad];
counterTask = [[UIApplication sharedApplication]
beginBackgroundTaskWithExpirationHandler:^{
// If you're worried about exceeding 10 minutes, handle it here
}];
count=0;
theTimer=[NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(countUp)
userInfo:nil
repeats:YES];
x: some other activity to be performed in the background
maybe another timer with a difference time interval
}
你怎麼會另外指定那x也會在後臺執行?
或者我誤解了它是如何工作的,以及何時調用beginBackgrounTaskWithExpirationHandler它是整個應用程序實際上將在後臺執行?如果是這種情況,那麼爲什麼需要一個任務標識符,因爲您只能啓動一個您的應用程序的任務?
如果情況並非如此,並且可以挑選不同的任務在後臺執行,那麼這是如何實現的?假設在這個例子中X是第二個具有不同間隔和不同過期條件的計時器,如果我希望計時器和x在後臺執行,那麼代碼是什麼樣子?換句話說如果代碼是這樣的:
- (void)viewDidLoad {
[super viewDidLoad];
counterTask = [[UIApplication sharedApplication]
beginBackgroundTaskWithExpirationHandler:^{
// If you're worried about exceeding 10 minutes, handle it here
}];
count=0;
theTimer=[NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(countUp)
userInfo:nil
repeats:YES];
theTimer2=[NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(aDifferentMethod)
userInfo:nil
repeats:YES];
theTimer3=[NSTimer scheduledTimerWithTimeInterval:10.0
target:self
selector:@selector(anotherDifferentMethod)
userInfo:nil
repeats:YES];
}
如何指定theTimer和theTimer2都在後臺執行,但theTimer3不?