后台抓取导致应用程序冻结而不是前台抓取

Posted

技术标签:

【中文标题】后台抓取导致应用程序冻结而不是前台抓取【英文标题】:background fetching causes app freeze than foreground fetching 【发布时间】:2015-04-28 10:54:27 【问题描述】:

我已经在 coredata 中实现了后台提取,但它仍然比正常提取冻结了几秒钟的应用程序。有什么我可以做的快速获取吗?似乎它仍在前台获取,不知道代码有什么问题。

- (void)sr_executeFetchRequest:(NSFetchRequest *)request completion:(void (^)(NSArray *objects, NSError *error))completion 

NSString *loginUser=[[NSUserDefaults standardUserDefaults] valueForKey:@"currentUser"];

AppDelegate *sharedDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSPersistentStoreCoordinator *coordinator = [sharedDelegate persistentStoreCoordinator];
NSManagedObjectContext *context = [sharedDelegate managedObjectContext];

NSManagedObjectContext *backgroundContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    backgroundContext.persistentStoreCoordinator = coordinator;

[backgroundContext performBlock:^

    // Fetch into shared persistent store in background thread
    NSError *error = nil;
    //        NSLog(@"BG thread===== ");

    NSArray *fetchedObjects = [backgroundContext executeFetchRequest:request error:&error];

    [context performBlock:^
        if (fetchedObjects) 
            // Collect object IDs
            NSMutableArray *mutObjectIds = [[NSMutableArray alloc] initWithCapacity:[fetchedObjects count]];
            for (NSManagedObject *obj in fetchedObjects) 
                [mutObjectIds addObject:obj.objectID];
    //                    NSLog(@"BG bg===== ");

            

            // Fault in objects into current context by object ID as they are available in the shared persistent store
            NSMutableArray *mutObjects = [[NSMutableArray alloc] initWithCapacity:[mutObjectIds count]];
            for (NSManagedObjectID *objectID in mutObjectIds) 
                NSManagedObject *obj = [context objectWithID:objectID];
                [mutObjects addObject:obj];
   //                    NSLog(@"BG fg===== ");

            

            if (completion) 
                NSArray *objects = [mutObjects copy];
                completion(objects, nil);
            
         else 
            if (completion) 
                completion(nil, error);
            
        
    ];
];

我在服务器中有一些记录,当后台到前台时,应用程序服务器将发送所有记录,并且从客户端我将所有数据保存到 coredata 中。保存时我需要检查这些数据是否已经存在,有时我需要在保存之前从数据库中获取一些数据,但是在这些时候我的应用程序被冻结了,只有在所有更新和保存完成后才能正常工作。

Profiler 跟踪 https://www.dropbox.com/s/6b1gykvs1pezrcp/Instruments4.trace.zip?dl=0

保存到数据库

     -(void)updateThreadEntityWithSyncDetails:(NSMutableDictionary *)inDictionary
  

 NSString *loginUser=[[NSUserDefaults standardUserDefaults] valueForKey:@"currentUser"];

 AppDelegate *sharedDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [sharedDelegate managedObjectContext];

  //    NSManagedObjectContext *writerContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
  //   [writerContext setPersistentStoreCoordinator:[sharedDelegate persistentStoreCoordinator]];
 ////    
  ////    // create main thread MOC
 //    context = [[NSManagedObjectContext alloc]        initWithConcurrencyType:NSMainQueueConcurrencyType];
    //    context.parentContext = writerContext;
  ////

NSManagedObjectContext *contextforThread = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];

contextforThread.parentContext = context;

[contextforThread performBlock:^




NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setReturnsObjectsAsFaults:NO];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"ThreadInfo"
                                          inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSPredicate *userPredicate = [NSPredicate predicateWithFormat:@"userEmail == %@",loginUser];
NSPredicate *threadPredicate = [NSPredicate predicateWithFormat:@"threadID == %@",[inDictionary valueForKey:@"thread"]];
NSPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates: @[userPredicate, threadPredicate]];
[fetchRequest setPredicate:compoundPredicate];

NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:nil];
for (ThreadInfo *threadInfo in fetchedObjects)

    if([[inDictionary allKeys] containsObject:@"userEmail"])
    
        if([inDictionary valueForKey:@"userEmail"]!=[NSNull null])
        
            threadInfo.userEmail=[inDictionary valueForKey:@"userEmail"];
        
    
    if([[inDictionary allKeys] containsObject:@"badgeValue"])
    
        if([inDictionary valueForKey:@"badgeValue"]!=[NSNull null])
        
            threadInfo.badgeValue=[inDictionary valueForKey:@"badgeValue"];
        
    

    if([[inDictionary allKeys] containsObject:@"thread"])
    
        if([inDictionary valueForKey:@"thread"]!=[NSNull null])
        
            threadInfo.threadID=[inDictionary valueForKey:@"thread"];
        
    
    if([[inDictionary allKeys] containsObject:@"key"])
    
        if([inDictionary valueForKey:@"key"]!=[NSNull null])
        
            threadInfo.threadKey=[inDictionary valueForKey:@"key"];
        
    
    if([[inDictionary allKeys] containsObject:@"secret_seed"])
    
        if([inDictionary valueForKey:@"secret_seed"]!=[NSNull null])
        
            threadInfo.threadSecret=[NSString stringWithFormat:@"%@",[inDictionary valueForKey:@"secret_seed"]];
        
    
    if([[inDictionary allKeys] containsObject:@"r_key"])
    
        if([inDictionary valueForKey:@"r_key"]!=[NSNull null])
        
            threadInfo.remoteKey=[inDictionary valueForKey:@"r_key"];
        
    
    if([[inDictionary allKeys] containsObject:@"solicitation"])
    
        if([inDictionary valueForKey:@"solicitation"]!=[NSNull null])
        
            threadInfo.solicitationID=[inDictionary valueForKey:@"solicitation"];
        
    
    if([[inDictionary allKeys] containsObject:@"r_secret"])
    
        if([inDictionary valueForKey:@"r_secret"]!=[NSNull null])
        
            threadInfo.remoteSecret=[inDictionary valueForKey:@"r_secret"];
        
    
    if([[inDictionary allKeys] containsObject:@"icon_idx"])
    
        if([inDictionary valueForKey:@"icon_idx"]!=[NSNull null])
        
            threadInfo.avatarIconIndex=[inDictionary valueForKey:@"icon_idx"];
        
    

    if([[inDictionary allKeys] containsObject:@"icon_color_idx"])
    
        if([inDictionary valueForKey:@"icon_color_idx"]!=[NSNull null])
        
            threadInfo.avatarColorIndex=[inDictionary valueForKey:@"icon_color_idx"];
        
    

    if([[inDictionary allKeys] containsObject:@"encrypted_r_secret"])
    
        if([inDictionary valueForKey:@"encrypted_r_secret"]!=[NSNull null])
        
            threadInfo.encryptedRemoteSecret=[inDictionary valueForKey:@"encrypted_r_secret"];
        
    
    if([[inDictionary allKeys] containsObject:@"isSystemMessage"])
    
        if([inDictionary valueForKey:@"isSystemMessage"]!=[NSNull null])
        
            threadInfo.isSystemMessage=[inDictionary valueForKey:@"isSystemMessage"];
        
    
    if([[inDictionary allKeys] containsObject:@"ref"])
    
        if([inDictionary valueForKey:@"ref"]!=[NSNull null])
        
            threadInfo.systemReferenceURL=[inDictionary valueForKey:@"ref"];
        
    
    if([[inDictionary allKeys] containsObject:@"url"])
    
        if([inDictionary valueForKey:@"url"]!=[NSNull null])
        
            threadInfo.systemMessageURL=[inDictionary valueForKey:@"url"];
        
    
    if([[inDictionary allKeys] containsObject:@"thumbnailImageURL"])
    
        if([inDictionary valueForKey:@"thumbnailImageURL"]!=[NSNull null])
        
            threadInfo.thumbnailImageURL=[inDictionary valueForKey:@"thumbnailImageURL"];
        
    
    if([[inDictionary allKeys] containsObject:@"from"])
    
        if([inDictionary valueForKey:@"from"]!=[NSNull null])
        
            threadInfo.receiverEmail=[inDictionary valueForKey:@"from"];
        
    
    if([[inDictionary allKeys] containsObject:@"isQuiz"])
    
        if([inDictionary valueForKey:@"isQuiz"]!=[NSNull null])
        
            threadInfo.isQuiz=[inDictionary valueForKey:@"isQuiz"];
        
    
    if([[inDictionary allKeys] containsObject:@"replied"])
    
        if([inDictionary valueForKey:@"replied"]!=[NSNull null])
        
            threadInfo.replied=[inDictionary valueForKey:@"replied"];
        
    
    if([[inDictionary allKeys] containsObject:@"owned"])
    
        if([inDictionary valueForKey:@"owned"]!=[NSNull null])
        
            BOOL isOwner=[[inDictionary valueForKey:@"owned"] boolValue];
            if([[inDictionary allKeys] containsObject:@"solicitation"])
            
                if([inDictionary valueForKey:@"solicitation"]!=[NSNull null])
                

                    if(isOwner)
                    

                        if ([[inDictionary valueForKey:@"solicitation"] isEqualToString:[inDictionary valueForKey:@"thread"]])
                        
                            threadInfo.isRequester=[NSNumber numberWithBool:YES];

                         else 
                            threadInfo.isSender=[NSNumber numberWithBool:YES];

                        

                    
                    else
                    
                        //                            threadInfo.isProvider=[NSNumber numberWithBool:YES];

                        if ([[inDictionary valueForKey:@"solicitation"] isEqualToString:[inDictionary valueForKey:@"thread"]])
                        
                            threadInfo.isProvider=[NSNumber numberWithBool:YES];

                         else 
                            threadInfo.isReceiver=[NSNumber numberWithBool:YES];

                        

                    
                
                else
                
                    if(isOwner)
                    
                        threadInfo.isSender=[NSNumber numberWithBool:YES];

                    
                    else
                    
                        threadInfo.isReceiver=[NSNumber numberWithBool:YES];

                    

                
            
            else
            
                if(isOwner)
                
                    threadInfo.isSender=[NSNumber numberWithBool:YES];

                
                else
                
                    threadInfo.isReceiver=[NSNumber numberWithBool:YES];

                
            


        

    
    if([[inDictionary allKeys] containsObject:@"options"])
    
        if([inDictionary valueForKey:@"options"]!=[NSNull null])
        
            NSMutableArray *accArray=[inDictionary valueForKey:@"options"];
            NSData *arrayData = [NSKeyedArchiver archivedDataWithRootObject:accArray];
            threadInfo.pollOptions = arrayData;
        
    

    if([[inDictionary allKeys] containsObject:@"isAnyReceiverActivity"])
    
        if([inDictionary valueForKey:@"isAnyReceiverActivity"]!=[NSNull null])
        
            threadInfo.isAnyReceiverActivity=[inDictionary valueForKey:@"isAnyReceiverActivity"];
        
    
    if([[inDictionary allKeys] containsObject:@"pollAnswerList"])
    
        if([inDictionary valueForKey:@"pollAnswerList"]!=[NSNull null])
        
            NSMutableDictionary *accDict=[inDictionary valueForKey:@"pollAnswerList"];
            NSData *dictData = [NSKeyedArchiver archivedDataWithRootObject:accDict];
            threadInfo.pollAnswerList = dictData;
        
    
    if([[inDictionary allKeys] containsObject:@"responseCount"])
    
        if([inDictionary valueForKey:@"responseCount"]!=[NSNull null])
        
            threadInfo.responseCount=[inDictionary valueForKey:@"responseCount"];
        
    

    if([[inDictionary allKeys] containsObject:@"isSender"])
    
        if([inDictionary valueForKey:@"isSender"]!=[NSNull null])
        
            threadInfo.isSender=[NSNumber numberWithBool:[[inDictionary valueForKey:@"isSender"] boolValue]];
        
    

    if([[inDictionary allKeys] containsObject:@"isRequester"])
    
        if([inDictionary valueForKey:@"isRequester"]!=[NSNull null])
        
            threadInfo.isRequester=[NSNumber numberWithBool:[[inDictionary valueForKey:@"isRequester"] boolValue]];
        
    
    if([[inDictionary allKeys] containsObject:@"image"])
    
        if([inDictionary valueForKey:@"image"]!=[NSNull null])
        
             threadInfo.image=[inDictionary valueForKey:@"image"];
        
    


    if([[inDictionary allKeys] containsObject:@"isReceiver"])
    
        if([inDictionary valueForKey:@"isReceiver"]!=[NSNull null])
        
            threadInfo.isReceiver=[NSNumber numberWithBool:[[inDictionary valueForKey:@"isReceiver"] boolValue]];
        
    
    if([[inDictionary allKeys] containsObject:@"colorCode"])
    
        if([inDictionary valueForKey:@"colorCode"]!=[NSNull null])
        
            threadInfo.colorCode=[inDictionary valueForKey:@"colorCode"];
        
    
    if([[inDictionary allKeys] containsObject:@"solicitationCount"])
    
        if([inDictionary valueForKey:@"solicitationCount"]!=[NSNull null])
        
            threadInfo.solicitationCount=[inDictionary valueForKey:@"solicitationCount"];
        
    
    if([[inDictionary allKeys] containsObject:@"solicitationNumber"])
    
        if([inDictionary valueForKey:@"solicitationNumber"]!=[NSNull null])
        
            threadInfo.solicitationNumber=[inDictionary valueForKey:@"solicitationNumber"];
        
    


    if([[inDictionary allKeys] containsObject:@"disliked"])
    
        if([inDictionary valueForKey:@"disliked"]!=[NSNull null])
        
            threadInfo.hasDislikes=[NSNumber numberWithBool:[[inDictionary valueForKey:@"disliked"] boolValue]];
        
    

    if([[inDictionary allKeys] containsObject:@"liked"])
    
        if([inDictionary valueForKey:@"liked"]!=[NSNull null])
        
            threadInfo.hasLikes=[NSNumber numberWithBool:[[inDictionary valueForKey:@"liked"] boolValue]];
        
    
    if([[inDictionary allKeys] containsObject:@"removed"])
    
        if([inDictionary valueForKey:@"removed"]!=[NSNull null])
        
            threadInfo.isThreadRemoved=[NSNumber numberWithBool:[[inDictionary valueForKey:@"removed"] boolValue]];
        
    
    if([[inDictionary allKeys] containsObject:@"closed"])
    
        if([inDictionary valueForKey:@"closed"]!=[NSNull null])
        
            threadInfo.isThreadEnded=[NSNumber numberWithBool:[[inDictionary valueForKey:@"closed"] boolValue]];
        
    
    if([[inDictionary allKeys] containsObject:@"blocked"])
    
        if([inDictionary valueForKey:@"blocked"]!=[NSNull null])
        
            threadInfo.isThreadBlocked=[NSNumber numberWithBool:[[inDictionary valueForKey:@"blocked"] boolValue]];
        
    
    if([[inDictionary allKeys] containsObject:@"hasComments"])
    
        if([inDictionary valueForKey:@"hasComments"]!=[NSNull null])
        
            threadInfo.hasComments=[NSNumber numberWithBool:[[inDictionary valueForKey:@"hasComments"] boolValue]];
        
    
    if([[inDictionary allKeys] containsObject:@"isProvider"])
    
        if([inDictionary valueForKey:@"isProvider"]!=[NSNull null])
        
            threadInfo.isProvider=[NSNumber numberWithBool:[[inDictionary valueForKey:@"isProvider"] boolValue]];
        
    

    if([[inDictionary allKeys] containsObject:@"messageDescription"])
    
        if([inDictionary valueForKey:@"messageDescription"]!=[NSNull null])
        
            threadInfo.messageDescription=[inDictionary valueForKey:@"messageDescription"];
        
    

    if([[inDictionary allKeys] containsObject:@"commentCount"])
    
        if([inDictionary valueForKey:@"commentCount"]!=[NSNull null])
        
            threadInfo.commentCount=[NSNumber numberWithInteger:[[inDictionary valueForKey:@"commentCount"] integerValue]];
        

    
    if([[inDictionary allKeys] containsObject:@"threadDate"])
    
        if([inDictionary valueForKey:@"threadDate"]!=[NSNull null])
        
            threadInfo.threadDate=[inDictionary valueForKey:@"threadDate"];
        
    
    if([[inDictionary allKeys] containsObject:@"receivedDate"])
    
        if([inDictionary valueForKey:@"receivedDate"]!=[NSNull null])
        
            threadInfo.receivedDate=[inDictionary valueForKey:@"receivedDate"];
        
    
    if([[inDictionary allKeys] containsObject:@"closedDate"])
    
        if([inDictionary valueForKey:@"closedDate"]!=[NSNull null])
        
            threadInfo.closedDate=[inDictionary valueForKey:@"closedDate"];
        
    

    if([[inDictionary allKeys] containsObject:@"blockedDate"])
    
        if([inDictionary valueForKey:@"blockedDate"]!=[NSNull null])
        
            threadInfo.blockedDate=[inDictionary valueForKey:@"blockedDate"];
        
    


    if([[inDictionary allKeys] containsObject:@"threadDescription"])
    
        if([inDictionary valueForKey:@"threadDescription"]!=[NSNull null])
        
            threadInfo.threadMessage=[inDictionary valueForKey:@"threadDescription"];
        
    

    if([[inDictionary allKeys] containsObject:@"receiverEmail"])
    
        if([inDictionary valueForKey:@"receiverEmail"]!=[NSNull null])
        
            threadInfo.receiverEmail=[inDictionary valueForKey:@"receiverEmail"];
        
    

    if([[inDictionary allKeys] containsObject:@"to"])
    
        if([inDictionary valueForKey:@"to"]!=[NSNull null])
        
            id toValue=[inDictionary valueForKey:@"to"];
            if([toValue isKindOfClass:[NSString class]])
            
                if ([toValue rangeOfString:@"@"].location != NSNotFound)
                
                    threadInfo.receiverEmail=[NSString stringWithFormat:@"%@",toValue];
                
            
            else
            
                NSMutableArray *accArray=[NSMutableArray arrayWithArray:toValue];
                NSData *arrayData = [NSKeyedArchiver archivedDataWithRootObject:accArray];
                threadInfo.solicitationList = arrayData;
            

        

    
    //Poll
    if([[inDictionary allKeys] containsObject:@"isPoll"])
    
        if([inDictionary valueForKey:@"isPoll"]!=[NSNull null])
        
            threadInfo.isPoll=[inDictionary valueForKey:@"isPoll"];
        
    
    if([[inDictionary allKeys] containsObject:@"type"])
    
        if([inDictionary valueForKey:@"type"]!=[NSNull null])
        
            threadInfo.pollType=[inDictionary valueForKey:@"type"];
        
    
    if([[inDictionary allKeys] containsObject:@"scope"])
    
        if([inDictionary valueForKey:@"scope"]!=[NSNull null])
        
            threadInfo.pollScope=[inDictionary valueForKey:@"scope"];
        
    
    if([[inDictionary allKeys] containsObject:@"isPollSender"])
    
        if([inDictionary valueForKey:@"isPollSender"]!=[NSNull null])
        
            threadInfo.isPollSender=[inDictionary valueForKey:@"isPollSender"];
        
    

    if([[inDictionary allKeys] containsObject:@"visibility"])
    
        if([inDictionary valueForKey:@"visibility"]!=[NSNull null])
        
            threadInfo.pollVisibility=[inDictionary valueForKey:@"visibility"];
        
    

    if([[inDictionary allKeys] containsObject:@"yesPercentage"])
    
        if([inDictionary valueForKey:@"yesPercentage"]!=[NSNull null])
        
            threadInfo.yesPercentage=[inDictionary valueForKey:@"yesPercentage"];
        
    
    if([[inDictionary allKeys] containsObject:@"noPercentage"])
    
        if([inDictionary valueForKey:@"noPercentage"]!=[NSNull null])
        
            threadInfo.noPercentage=[inDictionary valueForKey:@"noPercentage"];
        
    

    if([[inDictionary allKeys] containsObject:@"selectedOption"])
    
        if([inDictionary valueForKey:@"selectedOption"]!=[NSNull null])
        
            threadInfo.selectedOption=[inDictionary valueForKey:@"selectedOption"];
        
    
    if([[inDictionary allKeys] containsObject:@"selectedStar"])
    
        if([inDictionary valueForKey:@"selectedStar"]!=[NSNull null])
        
            threadInfo.selectedStar=[inDictionary valueForKey:@"selectedStar"];
        
    

            if([[inDictionary allKeys] containsObject:@"choice1Percentage"])
    
        if([inDictionary valueForKey:@"choice1Percentage"]!=[NSNull null])
        
            threadInfo.choice1Percentage=[inDictionary valueForKey:@"choice1Percentage"];
        
    
    if([[inDictionary allKeys] containsObject:@"choice2Percentage"])
    
        if([inDictionary valueForKey:@"choice2Percentage"]!=[NSNull null])
        
            threadInfo.choice2Percentage=[inDictionary valueForKey:@"choice2Percentage"];
        
    
    if([[inDictionary allKeys] containsObject:@"choice3Percentage"])
    
        if([inDictionary valueForKey:@"choice3Percentage"]!=[NSNull null])
        
            threadInfo.choice3Percentage=[inDictionary valueForKey:@"choice3Percentage"];
        
    
    if([[inDictionary allKeys] containsObject:@"choice4Percentage"])
    
        if([inDictionary valueForKey:@"choice4Percentage"]!=[NSNull null])
        
            threadInfo.choice4Percentage=[inDictionary valueForKey:@"choice4Percentage"];
        
    
    if([[inDictionary allKeys] containsObject:@"choice5Percentage"])
    
        if([inDictionary valueForKey:@"choice5Percentage"]!=[NSNull null])
        
            threadInfo.choice5Percentage=[inDictionary valueForKey:@"choice5Percentage"];
        
    

 

    NSError *error;
    if(![contextforThread save:&error]) 
        NSLog(@"Child error : %@",error);

    

    [context performBlock:^
        NSError *error;
        if(![context save:&error]) 
            NSLog(@"%@",error);
        
               ];
];


      

websocket // 不断从服务器获取数据

 - (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message
  
           NSDictionary *responseDict = [message JSONValue];
     NSArray *bodyDicta=[responseDict objectForKey:@"body"];
                for (int i=0; i<bodyDicta.count; i++) 
                    int responseCode=[[[[responseDict objectForKey:@"body"] objectAtIndex:i ] objectForKey:@"code"] intValue];


                    [self checkResponseCode:[bodyDicta objectAtIndex: i] indexvalue:responseCode isArray:1];
 

checkResponseCode

  -(void)checkResponseCode:(NSDictionary *)responseDict indexvalue:(int)code isArray:(int)flag 

   if(code==3608)
   
    [self manageGroupDetails:responseDict];
    

  if (code == 3602)// SCROLL ISSUE
   

    [self updateThreadWithSyncDetails:responseDict];
   
   if (code == 3603)
   

    [self updateCommentWithSyncDetails:responseDict];
   
   if(code==3607)// SCROLL ISSUE
  
    [self updateSolicitationWithSyncDetails:responseDict];
  

updatePollWithSyncDetails

-(void)updatePollWithSyncDetails:(NSDictionary *)responseDict
 
     BOOL isDuplicate=[[IXDataBaseManager sharedNetworkDataManager] checkForExistenceOfThreadDetailsForThreadID:[responseDict objectForKey:@"poll"]];
if(!isDuplicate)

             [[IXDataBaseManager sharedNetworkDataManager] updateThreadEntityWithSyncDetails:detailsDict];
 

updateSolicitationWithSyncDetails

 -(void)updateSolicitationWithSyncDetails:(NSDictionary *)inDictionary
 
 NSMutableDictionary *paramDict=[NSMutableDictionary dictionaryWithDictionary:inDictionary];
 NSString *userEmail=[[NSUserDefaults standardUserDefaults] valueForKey:@"currentUser"];
[paramDict setObject:[NSNumber numberWithBool:NO] forKey:@"isSystemMessage"];                          
                [paramDict setObject:message forKey:@"threadDescription"];
                ThreadInfo *threadInfo=[[IXDataBaseManager sharedNetworkDataManager] retrieveSolicitationInfoForThreadID:[inDictionary objectForKey:@"solicitation"]];
                [paramDict setObject:threadInfo.threadID forKey:@"thread"];
                [[IXDataBaseManager sharedNetworkDataManager] updateThreadEntityWithSyncDetails:paramDict];
            
        
 

【问题讨论】:

使用 xCode 调试器,您可以在块内添加断点并检查它们在哪个线程中执行。 是的,他们正在执行,我已经 NSlogged 的​​值。我的代码有什么问题吗? 【参考方案1】:

首先,您怎么知道是 fetch 阻塞了您的 UI?你在这上面运行过 Instruments 吗?如果有,痕迹在哪里?

如果你还没有,那么你需要停止,运行 Instruments,使用 Time Profiler 并找到块。使用跟踪链接更新您的问题,以便下载和查看。

如果没有在 Instruments 中查看此问题,您只是在猜测实际问题是什么。

更新 1

查看您提供的跟踪,我没有看到 Core Data 在主线程(或任何其他线程)上占用任何大量时间。我怀疑你在这里追错了。

您上面的代码不会为您节省任何时间。虽然它会将对象加载到NSPersistentStoreCoordinator 中以使您的主要NSManagedObjectContext 获取它们的速度稍快一些,但这并不重要。根据您的时间跟踪,您没有在 SQL 上花费任何时间(主线程上总共 132 毫秒)。

即使您的 SQL 调用花费了大量时间,它仍然会阻塞主线程,因为您在执行 fetch 时锁定了 NSPersistentStoreCoordinator

根据您提供的跟踪信息,您的问题出在您的 UI 中。您的大部分时间都花在-[IXInBoxViewController tableView;heightForRowAtIndexPath:] 上,这是锁定 UI 的常见位置。深入了解您的个人资料,找到昂贵的物品并修复它。

问题不在于核心数据。我建议删除此线程代码(添加线程不是性能解决方案)并返回使用 NSFetchedResultsController 和您的 UITableViewController 然后分析您的 UI 代码并修复缓慢的代码。

更新 2

我从服务器获取大量数据并不断节省核心数据。 .我正在使用 NSFetchedResultsController,因此必须重新加载每个储蓄表视图。现在我正在尝试一次保存少量数据,这是处理对核心数据的大量保存请求的正确方法吗?

您没有提供任何用于加载数据或保存数据的代码,因此无论您是否正确执行这些部分,我都无法权威地发言。

您加载的数据量无关紧要,只要它在后台线程的后台上下文中加载(我更喜欢使用 NSOperation 子类)并保存到 Core Data 中。 NSFetchedResultsController 会做正确的事情,除非您同时显示数据,否则对 UI 的影响将是最小的。如果数据正在加载到NSFetchedResultsController 并且相对不在屏幕上,那么它不会对性能产生重大影响。

运行仪器。每当有性能问题时,这是您的第一步。

如果您的数据加载速度很慢,请隔离速度较慢的行并解决它们。

如果您的保存速度很慢(不太可能),请将其分成小块。

但首先对其进行分析。否则你就是在黑暗中拍摄,只是在猜测。

【讨论】:

好的先生,但我通过评论那些需要保存和获取核心数据的方法发现了这个问题。之后它工作正常, 先生,我已经用确切的问题更新了我的问题 谢谢您,先生,我会尝试解决 UI 问题。我不断地从服务器获取大量数据并保存到核心数据。 .我正在使用 NSFetchedResultsController,因此必须重新加载每个储蓄表视图。现在我正在尝试一次保存少量数据,这是处理对核心数据的大量保存请求的正确方法吗? 请将其移至单独的问题并关闭此问题。 好的,先生,我打开了另一个链接***.com/questions/29959032/…【参考方案2】:

你有你的代码行...

backgroundContext.persistentStoreCoordinator = coordinator;

...在区块内。

在开始performBlock 之前尝试为您的 MOC 设置 PSC。

【讨论】:

其实这个抓取是在后台线程中完成的,那为什么主线程阻塞呢?我很混乱。你有什么解决办法吗? 抱歉之前没有注意到这一点,但是您将主要的 context 包裹在 backgroundContentperformBlock 方法中。这将阻止您的用户界面 我通过参考得到了这个方法。我的问题是获取阻止我的 UI,这就是我使用后台获取的原因,我不知道是否有另一种方法。你能帮助我吗?在这一点上真的卡住了。

以上是关于后台抓取导致应用程序冻结而不是前台抓取的主要内容,如果未能解决你的问题,请参考以下文章

asp 前台ajax提交的blob数据在后台怎么接受

核心数据:大后台抓取能否阻塞主线程抓取请求?

python&amp;php数据抓取爬虫分析与中介,有网址案例

QML 指针处理程序和处理抓取更改

抓取Google Play商店应用

linux 抓屏截图