gpt4 book ai didi

iphone - 在后台线程中更新托管对象并在主线程中显示它们,出了什么问题

转载 作者:行者123 更新时间:2023-12-03 20:28:58 24 4
gpt4 key购买 nike

晚上好,

我在 CoreData 和并发方面遇到了一些问题,所以我尝试了最简单的代码,但它仍然不起作用。你能指出我哪里错了吗?

我创建了一个“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

我有一个 View Controller ,它显示我的 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

onCoreDataUpdate 方法中获取的 block 对象似乎有错误的数据。

我哪里错了?

问候,昆汀

最佳答案

-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;
}

关于iphone - 在后台线程中更新托管对象并在主线程中显示它们,出了什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4821813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com