我正在研究一個iphone應用程序,偶爾會在後臺觸發一個任務來重新排列某些數據並將其上傳到服務器。我使用了很多Grand Central Dispatch (GCD) with CoreData的原理來運行,因爲我正在編輯持久存儲在Core Data中的對象,但代碼只是偶爾地完成運行,儘管應用程序說它幾乎還剩下600秒的執行時間。後臺任務塊功能沒有完成
我正在使用的代碼:
__block UIBackgroundTaskIdentifier bgTask;
UIApplication *application = [UIApplication sharedApplication]; //Get the shared application instance
NSLog(@"BackgroundTimeRemaining before block: %f", application.backgroundTimeRemaining);
bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
// Clean up any unfinished task business by marking where you.
// stopped or ending the task outright.
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Do the work associated with the task, preferably in chunks.
NSLog(@"BackgroundTimeRemaining after block: %f", application.backgroundTimeRemaining);
NSLog(@"Fixing item in the background");
//Create secondary managed object context for new thread
NSManagedObjectContext *backgroundContext = [[NSManagedObjectContext alloc] init];
[backgroundContext setPersistentStoreCoordinator:[self.managedObjectContext persistentStoreCoordinator]];
/* Save the background context and handle the save notification */
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(backgroundContextDidSave:)
name:NSManagedObjectContextDidSaveNotification
object:backgroundContext];
//creating runloop to kill location manager when done
NSDate *stopDate = [[NSDate date] dateByAddingTimeInterval:60];
[[NSRunLoop currentRunLoop] runUntilDate:stopDate];
NSLog(@"Stop time = %@", stopDate);
MasterViewController *masterViewContoller = [[MasterViewController alloc] init];
masterViewContoller.managedObjectContext = backgroundContext;
[[masterViewContoller locationManager] startUpdatingLocation];
NSLog(@"Successfully fired up masterViewController class");
[masterViewContoller adjustDataInBackground:FALSE];
NSLog(@"Fixed Object!");
//save background context
[backgroundContext save:NULL];
//unregister self for notifications
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSManagedObjectContextDidSaveNotification
object:backgroundContext];
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
});
的問題是,「adjustDataInBackground:FALSE」是調用額外的支持方法(包括創建和核心數據對象的保存)一個相當長的方法,當後臺任務不允許所有這些方法完成它會破壞我的數據。
有沒有更好的方法來處理這種操作?我是否需要直接將所有原始代碼放入後臺任務塊中?
謝謝 - 這是我見過的最完整的代碼。我想強調任何讀取異步連接的人:您肯定希望在像這樣的異步塊中執行同步URL請求。 – LordParsley 2013-11-21 12:38:54