在我的应用程序中,执行获取请求应用程序时随机冻结。我尝试了多个选择,如@synchronized和performblock仍然挂起发生。下面是我的第一个获取请求块。应用程序随机挂起此获取请求。
+(BXXXX *)getDetailsById:(NSNumber *)Id
{
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
NSEntityDescription *entityDescription = [NSEntityDescription
entityForName:@"BXXXX" inManagedObjectContext:[SDataManager managedObjectContext]];
[fetch setEntity:entityDescription];
[fetch setPredicate:[NSPredicate predicateWithFormat:
@"(BId = %@)",Id]];
__block NSArray *bDetails;
[[SDataManager managedObjectContext] performBlockAndWait:^{
NSError *error = nil;
bDetails = [[SDataManager managedObjectContext] executeFetchRequest:fetch error:&error];
}];
if([bDetails count] == 1)
return [bDetails objectAtIndex:0];
else
return nil;
}
// MY管理对象上下文声明
+(NSManagedObjectContext *)managedObjectContext
{
static NSManagedObjectContext *managedObjectContext;
if(managedObjectContext!=nil){
return managedObjectContext;
}
@try {
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[managedObjectContext setPersistentStoreCoordinator: coordinator];
}
}
@catch (NSException *exception) {
NSLog(@"Exception occur %@",exception);
}
return managedObjectContext;
}
请指导我解决此问题。我努力了,但我现在还无法解决这个问题。
答案 0 :(得分:2)
managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
您的托管对象上下文将在主队列上执行所有操作。这将阻止主事件循环并导致您的应用似乎挂起。
将工作移出主队列。请参阅Core Data Concurrency Guide。
答案 1 :(得分:0)
I have fixed this issue by creating two managed object context like this.
// Base
+(NSManagedObjectContext *)managedObjectContext
{
static NSManagedObjectContext *managedObjectContext;
if(managedObjectContext!=nil){
return managedObjectContext;
}
@try {
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[managedObjectContext setPersistentStoreCoordinator: coordinator];
}
}
@catch (NSException *exception) {
NSLog(@"Exception occur %@",exception);
}
return managedObjectContext;
}
//Child
+(NSManagedObjectContext *)childManagedObjectContext
{
static NSManagedObjectContext *managedObjectContext;
if(managedObjectContext!=nil){
return managedObjectContext;
}
@try {
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[managedObjectContext setPersistentStoreCoordinator: coordinator];
}
}
@catch (NSException *exception) {
NSLog(@"Exception occur %@",exception);
}
return managedObjectContext;
}
用于执行获取请求我使用了并发类型的子管理对象上下文作为NSPrivateQueueConcurrencyType。它对我来说很好。现在UI挂起不存在。