提前感谢您的帮助。我正在尝试创建一个应用程序,允许用户回答问题并为一群人添加自己的问题。我正在从解析下载库存问题,由于各种原因,我需要将这些问题按特定顺序加载到主数组中。我试图通过串行GCD队列来实现这一点,但这始终在预期结果和相反结果之间切换。它对我没有意义,但我不能动摇它可能与解析查询使用的异步下载请求有关的感觉,这里没有其他答案解决。
这是我的代码:
- (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];
}
}];
}
再次,非常感谢任何帮助!
答案 0 :(得分:3)
您在这里做的是将序列化异步调用到Parse库。因此,虽然每个-[PFQuery findObjectsInBackgroundWithBlock:]
同步排队,但这些函数本身是异步的。您可以尝试使用同步方法-[PFQuery findObjectsWithError:]
方法,以确保方法调用以正确的顺序返回。