代码块中的变量集不保留其值

时间:2015-04-22 21:33:01

标签: ios objective-c parse-platform

新手问题...我试图在代码块中设置变量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);

1 个答案:

答案 0 :(得分:0)

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

示例:

-(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);
}