Question

Hi good people I'm trying to prevent the freezing with

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{ CODE });

but I don't know how to use function.. I don't know where to put the managedObjectContext and how to use this dispatch_async my code is:

- (void)updateFacebookFriendsHighScore{
    NSFetchRequest *requestche =[NSFetchRequest fetchRequestWithEntityName:@"Time"];
    [requestche setReturnsObjectsAsFaults:NO];
    NSPredicate *predicate=[NSPredicate predicateWithFormat:@"timeid==1"];
    requestche.predicate=predicate;
    NSArray *getIDTime = [self.managedObjectContext executeFetchRequest:requestche error:nil];
    NSString *getTheTime = [[getIDTime valueForKey:@"time"] componentsJoinedByString:@""];
    NSNumber *timeInInt = [NSNumber numberWithInteger: [getTheTime intValue]];
    int timeFromDB = [timeInInt intValue];
    timeFromDB = timeFromDB + 509;
    int timeNow = [[NSDate date] timeIntervalSince1970];
    if(timeNow > timeFromDB){
        NSFetchRequest *updateHighScoreRequest = [NSFetchRequest fetchRequestWithEntityName:@"Friends"];
        [updateHighScoreRequest setReturnsObjectsAsFaults:NO];
        NSArray *friendsToUpdate = [self.managedObjectContext executeFetchRequest:updateHighScoreRequest error:nil];
        for(NSArray *friendId in friendsToUpdate){
            NSString *getFriendId = [friendId valueForKey:@"fbid"] ;
            NSString *siteURL = [NSString stringWithFormat:@"http://www.example.com/example.php?fbid=%@", getFriendId];
            NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:siteURL]];
            [NSURLConnection sendAsynchronousRequest:urlRequest queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                NSString *resultsFromDB = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                NSNumber *theScoreForUpdate = [NSNumber numberWithInt:[resultsFromDB intValue]];
                NSFetchRequest *updateTheHighScoreRequest = [NSFetchRequest fetchRequestWithEntityName:@"Friends"];
                NSPredicate *updateTheHighScorePredicate = [NSPredicate predicateWithFormat:@"fbid==%@",getFriendId];
                updateTheHighScoreRequest.predicate=updateTheHighScorePredicate;
                Friends *setScore = [[self.managedObjectContext executeFetchRequest:updateTheHighScoreRequest error:nil] lastObject];
                NSLog(@"%@", setScore);
                [setScore setValue:theScoreForUpdate forKey:@"score"];
                [self.managedObjectContext save:nil];
                data = nil;
                resultsFromDB = nil;
                theScoreForUpdate = nil;
                setScore = nil;
         }];
        updateHighScoreRequest = nil;
        }
    }
    requestche = nil;
}

This code gets the time from database and update the highscore after 509 seconds from the CD result and when I run this request my app freeze ( DEADLOCK ). I am from Bulgaria and I'm trying to learn Objective C. Here we don't have schools for this our country is very bad in all instance and Bulgaria is last in Europe Union... Can some serious and good person help me with my code or explane how works everything in Objective C or only help me with this ?

Was it helpful?

Solution

Try this code. To keep the application as simple as possible, never take the Core data code out of the main thread i.e. any thing related to self.managedObjectContext such as save or executing fetch requests. It is because Core data is not thread safe and you will have to device a strategy to handle that. I am assuming that your application is straight forward and you don't need such a strategy. So, please try to keep it as simple as possible and always perform the core data operations (save, execute) on main thread. dispatch_async(dispatch_get_main_queue(), ^{ code }); will execute it on main thread.

-(void) updateFacebookFriendsHighScore
{
    dispatch_async(dispatch_get_main_queue(), ^{

        NSFetchRequest *requestche =[NSFetchRequest fetchRequestWithEntityName:@"Time"];
        [requestche setReturnsObjectsAsFaults:NO];
        NSPredicate *predicate=[NSPredicate predicateWithFormat:@"timeid==1"];
        requestche.predicate=predicate;
        NSArray *getIDTime = [self.managedObjectContext executeFetchRequest:requestche error:nil];
        NSString *getTheTime = [[getIDTime valueForKey:@"time"] componentsJoinedByString:@""];
        NSNumber *timeInInt = [NSNumber numberWithInteger: [getTheTime intValue]];
        int timeFromDB = [timeInInt intValue];
        timeFromDB = timeFromDB + 509;
        int timeNow = [[NSDate date] timeIntervalSince1970];
        if(timeNow > timeFromDB){
            NSFetchRequest *updateHighScoreRequest = [NSFetchRequest fetchRequestWithEntityName:@"Friends"];
            [updateHighScoreRequest setReturnsObjectsAsFaults:NO];
            NSArray *friendsToUpdate = [self.managedObjectContext executeFetchRequest:updateHighScoreRequest error:nil];
            for(NSArray *friendId in friendsToUpdate){
                NSString *getFriendId = [friendId valueForKey:@"fbid"] ;
                NSString *siteURL = [NSString stringWithFormat:@"http://www.example.com/example.php?fbid=%@", getFriendId];
                NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:siteURL]];
                [NSURLConnection sendAsynchronousRequest:urlRequest queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                    NSString *resultsFromDB = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                    NSNumber *theScoreForUpdate = [NSNumber numberWithInt:[resultsFromDB intValue]];
                    NSFetchRequest *updateTheHighScoreRequest = [NSFetchRequest fetchRequestWithEntityName:@"Friends"];
                    NSPredicate *updateTheHighScorePredicate = [NSPredicate predicateWithFormat:@"fbid==%@",getFriendId];
                    updateTheHighScoreRequest.predicate=updateTheHighScorePredicate;
                    Friends *setScore = [[self.managedObjectContext executeFetchRequest:updateTheHighScoreRequest error:nil] lastObject];
                    NSLog(@"%@", setScore);
                    [setScore setValue:theScoreForUpdate forKey:@"score"];
                    [self.managedObjectContext save:nil];
                    data = nil;
                    resultsFromDB = nil;
                    theScoreForUpdate = nil;
                    setScore = nil;
                }];
                updateHighScoreRequest = nil;
            }
        }
        requestche = nil;

    });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top