Ios 代码块中设置的变量不保留其值

Ios 代码块中设置的变量不保留其值,ios,objective-c,parse-platform,Ios,Objective C,Parse Platform,新手问题。。。我试图在代码块中设置变量self.projectName,但在代码块外调用它时,该值不会保留。在阅读了更多关于代码块的内容后,似乎有一些关于值何时可用的规则,但我仍然不清楚为什么我不能设置值以供以后使用…任何帮助都将不胜感激 PFQuery *query = [PFQuery queryWithClassName:@"ScheduledProjects"]; [query findObjectsInBackgroundWithBlock:^(NSArray *projects, N

新手问题。。。我试图在代码块中设置变量self.projectName,但在代码块外调用它时,该值不会保留。在阅读了更多关于代码块的内容后,似乎有一些关于值何时可用的规则,但我仍然不清楚为什么我不能设置值以供以后使用…任何帮助都将不胜感激

PFQuery *query = [PFQuery queryWithClassName:@"ScheduledProjects"];
[query findObjectsInBackgroundWithBlock:^(NSArray *projects, NSError *error) {
    if (!error) {
        PFObject *project = [projects objectAtIndex:indexPath.row];
        self.projectName = project[@"name"];
    } else {
        // Log details of the failure
        NSLog(@"Error: %@ %@", error, [error userInfo]);
    }
}];

NSLog (@"project name = %@",self.projectName);

块是异步调用的,这意味着在定义它之后,您不知道它将在何时完成执行。 要使用该变量,请尝试创建回调函数并在块的末尾调用它。在那里你肯定知道它已经被执行了

例如:

-(void)yourMethod{

PFQuery *query = [PFQuery queryWithClassName:@"ScheduledProjects"];
[query findObjectsInBackgroundWithBlock:^(NSArray *projects, NSError *error) {
    if (!error) {
            PFObject *project = [projects objectAtIndex:indexPath.row];
        self.projectName = project[@"name"];
        [self callback];//You call the method when your block is finished
    } else {
        // Log details of the failure
        NSLog(@"Error: %@ %@", error, [error userInfo]);
        //Here you could call a different callback for error handling (or passing a success param)
    }
}];

}

-(void) callback{
    //Here you know the code has been executed
    NSLog (@"project name = %@",self.projectName);
}

请告诉我们该属性是如何定义的。这可能是属性
分配
的问题。另外,块后的代码(块是异步的)在块完成之前运行,因此它还没有值。了解异步处理。完全有意义。非常感谢你的帮助!