サーバーからアプリケーションに非同期でデータを取得しようとすると、同様の問題が発生しました。私の方法は少し異なりますが、基本的にはここです(これは4.3プロジェクトなので、ARCはありません)。
次のメソッドは、私のDataUpdaterシングルトンにあります。この第1の方法は、アプリケーションの起動時に呼び出されます。
- (void) update { //download the updates on a new thread
[NSThread detachNewThreadSelector:@selector(updateThread)
toTarget:self withObject:nil];
}
はそれだけで救われるために、メインスレッドに戻ってそれを渡し、その後、APIからコンテンツをダウンロードするための責任があり、このセレクタ、とのスレッドを初期化します。
- (void) updateThread { //the actual update thread
//New thread, new auto-release pool
//(dunno if you need to do anything fancy for ARC)
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
//...
//YOUR CODE TO DOWNLOAD (BUT *NOT* SAVE) DATA FROM THE SERVER
//DON'T CREATE ANY MANAGED OBJECTS HERE
//...
//Pass the data to the main thread to perform
//the commit to the Core Data Model
[self performSelectorOnMainThread:@selector(saveUpdate:)
withObject:data waitUntilDone:NO];
//kill the thread & the auto-release pool
[NSThread exit];
[pool release];
}
メインスレッドに戻り、データがコアデータモデルに追加され、コンテキストが保存されます。あなたの周りに管理オブジェクトコンテキストを渡す必要はありません(!あなたが本当に複数の質問をするはずの)唯一の問題の最初の部分に対処する
- (void) saveUpdate:(NSArray *) data {
//add the objects to your Core Data Model
//and save context
NSError * error = nil;
[[[CoreManager defaultCoreManager] CoreContext] save:&error];
if (error) {
[NSException raise:@"Unable to save data update"
format:@"Reason: %@", [error localizedDescription]];
} else {
[[NSNotificationCenter defaultCenter] postNotification:
[NSNotification notificationWithName:@"DONE" object:nil]];
}
}
このクラスはどのように呼び出されましたか? – Bot
「基本的にviewDidLoadで」コンテキストを取得する必要があるときは、単に 'NSManagedObjectContext * context = [[DataManager sharedInstance] managedObjectContext];を実行しますか? – Bot
うん、それは基本的にそれです。 – Kevin