晚上好,
我在CoreData和Concurrency方面遇到了一些问题,所以我尝试了最简单的代码,但仍然无效.你能告诉我我错在哪里吗?
我创建了一个"DataManager"来更新一个CoreData对象
@implementation OBSDataManager
@synthesize persistentStoreCoordinator;
- (OBSDataManager *)initWithPersistentStoreCoordinator:(NSPersistentStoreCoordinator *)aPersistentStoreCoordinator {
if (self = [super init]) {
self.persistentStoreCoordinator = aPersistentStoreCoordinator;
}
return self;
}
- (void)dealloc {
[persistentStoreCoordinator release];
[super dealloc];
}
- (void)start {
[self performSelectorInBackground:@selector(updateData) withObject:nil];
}
- (void)updateData {
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
context.persistentStoreCoordinator = self.persistentStoreCoordinator;
// get chunk if it exists, or create it
OBSChunk *chunk = [OBSChunk theChunkInContext:context];
if (!chunk) {
chunk = [NSEntityDescription insertNewObjectForEntityForName:@"Chunk"
inManagedObjectContext:context];
}
while (1) {
// update content
chunk.text = [[NSDate date] description];
// save it
NSError *error;
if ([context save:&error]) {
NSLog(@"Problem on save");
}
}
[context release];
}
@end
Run Code Online (Sandbox Code Playgroud)
我有一个视图控制器,显示我的CoreData对象的内容
@implementation MainViewController
@synthesize managedObjectContext;
@synthesize label;
#pragma mark -
#pragma mark UIViewController
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(onCoreDataUpdate:)
name:NSManagedObjectContextDidSaveNotification
object:nil];
}
- (void)viewDidUnload {
[super viewDidUnload];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSManagedObjectContextDidSaveNotification
object:nil];
}
#pragma mark -
#pragma mark private
- (void)onCoreDataUpdate:(NSNotification *)updateNotification {
[self.managedObjectContext mergeChangesFromContextDidSaveNotification:updateNotification];
OBSChunk *chunk = [OBSChunk theChunkInContext:self.managedObjectContext];
self.label.text = chunk.text;
}
@end
Run Code Online (Sandbox Code Playgroud)
似乎在onCoreDataUpdate方法中获取的块对象具有出现故障的数据.
我哪里错了?
问候,昆汀
-onCoreDataUpdate:正在后台线程上调用.在他们发送的帖子上收到通知.您需要回调主线程以实际处理更新.您可以使用以下内容来处理此问题:
- (void)onCoreDataUpdate:(NSNotification *)updateNotification {
if (![NSThread isMainThread]) {
[self performSelectorOnMainThread:_cmd withObject:updateNotification waitUntilDone:NO];
return;
}
[self.managedObjectContext mergeChangesFromContextDidSaveNotification:updateNotification];
OBSChunk *chunk = [OBSChunk theChunkInContext:self.managedObjectContext];
self.label.text = chunk.text;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
814 次 |
| 最近记录: |