我遇到这个一直困扰着我的奇怪问题,我正在后台线程中更新一个正确保存的对象
NSFetchRequest *fetchRequest1 = [[NSFetchRequest alloc] init];
NSEntityDescription *entity1 = [NSEntityDescription entityForName:@"STMilestone"
inManagedObjectContext:tmpContext];
[fetchRequest1 setEntity:entity1];
[fetchRequest1 setReturnsObjectsAsFaults:NO];
NSError *error;
NSString *idNum = [obj valueForKey:@"id"];
// NSUInteger TrackerExists = [tmpContext countForFetchRequest:fetchRequest1 error:&error];
[fetchRequest1 setPredicate:[NSPredicate predicateWithFormat:@"identiferNumber = %@", idNum]];
NSArray *logs = [tmpContext executeFetchRequest:fetchRequest1 error:&error];
NSManagedObject *updateObj = [logs objectAtIndex:0];
[updateObj setValue:[NSNumber numberWithInt:20] forKey:@"progress"];
当我在同一个后台线程中获取此对象时,会获得正确的更新值
然而,当我在主线程上获取此更新值时,它返回旧值,然后当我清除缓存并重新加载应用程序时,它会提取正确的数据
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"STTracker"
inManagedObjectContext:context];
[fetchRequest setEntity:entity];
[fetchRequest setReturnsObjectsAsFaults:NO];
NSError *error = nil;
NSMutableArray *array = [NSMutableArray arrayWithArray:[context executeFetchRequest:fetchRequest error:&error]];
我认为这可能是一个上下文问题,我的后台线程上下文是用这个
创建的AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *tmpContext = [[NSManagedObjectContext alloc] init];
tmpContext.persistentStoreCoordinator = [appDelegate persistenceCoordinator];
,主线程是
NSPersistentStoreCoordinator *coordinator = [self persistenceCoordinator];
if(coordinator != nil)
{
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
NSUndoManager *undoManager = [[NSUndoManager alloc] init];
[undoManager setGroupsByEvent:NO];
[_managedObjectContext setUndoManager:undoManager];
}
[_managedObjectContext setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy];
但是我已经更新了我的应用程序中的其他对象并且它们正在被触及,所以任何有关为什么会发生这种情况的帮助或见解都会很棒
答案 0 :(得分:1)
这不起作用:
NSManagedObjectContext *tmpContext = [[NSManagedObjectContext alloc] init];
您需要使用正确的并发类型初始化上下文,并为其分配正确的父上下文(或持久性存储协调器)。参见文档
当正确设置子和父上下文时,您save
子上下文并不真正写入持久存储但只是"推送"更改到父上下文。再次保存父上下文后,更改将写入存储。