gpt4 book ai didi

ios - 在 performBlock 中多次保存上下文

转载 作者:行者123 更新时间:2023-11-29 11:31:41 25 4
gpt4 key购买 nike

我有流程,我应该创建对象并将其保存在 CoreData 中。但是按照流程,我需要每 X 秒更新一次对象并使用保存的上下文更新它。并且因为有可能终止 coredata 中的应用程序应该是对象的“最后更新版本”。问题是保存上下文后,核心数据不再保存。双重保存不起作用的示例:

dispatch_semaphore_t waitTodoA = dispatch_semaphore_create(0);
NSManagedObjectContext *contextA = [CoreDataManager backgroundObjectContext];
[contextA performBlock:^{

PlaceObject* placeObject = [NSEntityDescription insertNewObjectForEntityForName:@"Places" inManagedObjectContext:contextA];
placeObject.type = @"Flat";
placeObject.timestamp = [[NSDate date] timeIntervalSince1970];
[CoreDataManager saveContext:contextA];

placeObject.address = @"Sunny beach ave. 1";
placeObject.coordinates = @"0.0,0.0";
[CoreDataManager saveContext:contextA];

dispatch_semaphore_signal(waitTodoA);
}];
dispatch_semaphore_wait(waitTodoA, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)));

最佳答案

好的,我明白你现在要测试什么了。答案是它非常适合我。我将以下代码粘贴到我基于文档的 Core Data 应用程序的文档子类中 -readFromURL::: 的尾端:

[self.managedObjectContext performBlock:^{
Stark* stark = [NSEntityDescription insertNewObjectForEntityForName:@"Stark_entity"
inManagedObjectContext:self.managedObjectContext];

BOOL ok ;
NSError* error = nil;
NSLog(@"Testing two saves in %@", self);

stark.name = @"David";
stark.rating = @(3);
ok = [self.managedObjectContext save:&error];
NSLog(@"First Save ok=%hhd error = %@", ok, error);

stark.url = @"http://example.com";
stark.comments = @"Did it work?";
ok = [self.managedObjectContext save:&error];
NSLog(@"Second Save ok=%hhd error = %@", ok, error);
}];

运行此代码后,NSLogs 打印:

Testing two saves in BkmxDoc 0x100d308f0 "Test.bmco"
First Save ok=1 error = (null)
Second Save ok=1 error = (null)

并且,在检查 SQLite 文件后,我发现确实插入了新对象,并且具有由上述代码分配的所有四个属性值。

我同意@vadian 的观点,在其中使用 dispatch_semaphore 很奇怪,尽管我看不出有任何原因会导致保存失败。只是为了证明,在随后的测试中,我使用 dispatch_semaphore 添加了这三行,重新测试,它仍然有效。

问题最可能的来源是您对 CoreDataManager 的使用。请注意,在我的代码中,我只使用了原始的 `-[NSManagedObjectContext save:]。

关于ios - 在 performBlock 中多次保存上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52873678/

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