1

Заранее благодарим за любую помощь. Я пытаюсь создать приложение, которое позволяет пользователю отвечать на вопросы и добавлять их для группы людей. Я загружаю вопросы запаса из разбора, и по разным причинам мне нужно, чтобы этот вопрос загружался в основной массив в определенном порядке. Я пытаюсь выполнить это с последовательной очередью GCD, но это последовательно переключается между ожидаемым результатом и противоположным результатом. Для меня это не имеет смысла, но я не могу поколебать ощущение, что он может иметь какое-то отношение к асинхронным запросам загрузки, используемым в синтаксическом анализе, и ни один из других ответов здесь не указан.Последовательность серий GCD, похоже, не выполняется серийно при использовании Parse

Вот мой код:

- (void)viewDidLoad{ 
[super viewDidLoad]; 


//Load the question with Central Dispatch to ensure load order 
dispatch_queue_t my_queue = dispatch_queue_create("com.suresh.methodsqueue", NULL); 
dispatch_async(my_queue, ^{ 
    //Load the inital questions 
    if (self.objectQuestions == nil) { 
     [self loadQuestionsWithClassName:@"FirstHundred"]; 
    } 
}); 
dispatch_async(my_queue, ^{ 
    //Load the paid questions 
    [self loadQuestionsWithClassName:@"PaidQuestions"]; 
}); 
} 

Это вспомогательный метод я писал:

-(void)loadQuestionsWithClassName:(NSString *)tempString { 
//Query from Parse 
PFQuery *query = [PFQuery queryWithClassName:tempString]; 
[query orderByAscending:@"createdAt"]; 
[query findObjectsInBackgroundWithBlock:^(NSArray *firstobjects, NSError *error) { 
    if (!error) { 
     // The find succeeded. Relay that information. 
     NSLog(@"Successfully retrieved %lu items from user %@", (unsigned long)firstobjects.count, [[PFUser currentUser] objectId]); 

     //Clear the objectQuestions temporary array and load the new Questions with the QuestionAndAnswers class 
     self.objectQuestions = nil; 
     self.objectQuestions = (NSMutableArray *)firstobjects; 
     int n; 
     int x = 0; 
     int z = (int)[[MainQuestionList sharedInstance].mainQuestionList count]; 
     for (n=(int)[[MainQuestionList sharedInstance].mainQuestionList count]; n<[self.objectQuestions count]+z; ++n) 
     { 
      QuestionsAndAnswers *startQuestion = [[QuestionsAndAnswers alloc] init]; 
      startQuestion.questionNumber = &(n)+1; 
      PFObject *object = [self.objectQuestions objectAtIndex:x]; 
      startQuestion.question = [object objectForKey:@"question"]; 
      startQuestion.answer = 0; 
      startQuestion.starred = NO; 
      startQuestion.answered = NO; 
      startQuestion.category = [object objectForKey:@"Category"]; 
      ++x; 


      [[MainQuestionList sharedInstance].mainQuestionList addObject:startQuestion]; 
     } 

     //Find the first unanswered question 
     while ([[MainQuestionList sharedInstance].mainQuestionList[self.mainQuestionNumber] answered] == YES) { 
      ++self.mainQuestionNumber; 
     }; 
    } else { 
     // Log details of the failure 
     NSLog(@"Error: %@ %@", error, [error userInfo]); 
     UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Sorry!" message:@"We are sorry. Something seems to have gone wrong loading the app. Please check your internet connection and restart the app!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
     [alertView show]; 
    } 
}]; 

} 

Опять же, любая помощь очень ценится!

ответ

3

Что вы здесь делаете, это сериализация асинхронных вызовов в библиотеке Parse. Поэтому, хотя каждый -[PFQuery findObjectsInBackgroundWithBlock:] синхронно ставится в очередь, эти функции сами по себе являются асинхронными. Вы можете попробовать использовать метод -[PFQuery findObjectsWithError:], синхронный метод, чтобы гарантировать, что ваш метод вызывает возврат в правильном порядке.

Смежные вопросы