目标C保留一个块对属性所做的更改

时间:2011-09-17 09:44:44

标签: objective-c ios asihttprequest objective-c-blocks

由于某些原因,此代码不起作用:

[request setCompletionBlock:^{
    NSString *response = [request responseString];
    NSDictionary *data = [response JSONValue];
    NSArray *events = (NSArray *)[data objectForKey:@"objects"];

    for (NSMutableDictionary *event in events){

        /* experimental code*/
        NSString *urlString = [NSString 
                               stringWithFormat:
                               @"http://localhost:8000%@?format=json",
                               [event objectForKey:@"tournament"]];

        NSURL *url2 = [NSURL URLWithString:urlString];
        ASIHTTPRequest *request2 = [ASIHTTPRequest requestWithURL:url2];
        [request2 setCompletionBlock:^{
            NSString *responseString = [request2 responseString];
            NSDictionary *tournamentDict = [responseString JSONValue];
            self.tournamentString = [tournamentDict objectForKey:@"tournament"]; 
        }];
        [request2 startAsynchronous];

        /* end experimental code */
        NSLog(@"%@", self.tournamentString);
        [mutableArray addObject:event];
    }
    self.eventsArray = mutableArray;
    [MBProgressHUD hideHUDForView:self.view animated:YES];

    [self.tableView reloadData];
}];

所以这里有2个异步请求,我一个接一个地触发。我想在第二个请求执行后更改属性tournamentText的值。

在第二个请求的完成块内,当我NSLog self.tournamentText时,它显示我想要检索的文本。

在块之外,NSLog产生零。

如何保留对self.tournamentText的更改?提前致谢!如果我错过了关于此的Apple文档,请告诉我。

1 个答案:

答案 0 :(得分:1)

您应该将__block存储类型修饰符应用于变量(块外)。

__阻止NSDictionary * tournamentDict;

有关详细信息,请参阅Apple的documentation on interaction between blocks and variables(在“块编程主题”中)。

顺便说一句,你确实意识到你在一个区块内有一个区块,而不是一个接一个的两个单独的区块?要保留对第二个块之外的变量的更改,请尝试以下操作:

[request setCompletionBlock:^{
    NSString *response = [request responseString];
    NSDictionary *data = [response JSONValue];
    NSArray *events = (NSArray *)[data objectForKey:@"objects"];

    for (NSMutableDictionary *event in events){

        /* experimental code*/
        NSString *urlString = [NSString 
                               stringWithFormat:
                               @"http://localhost:8000%@?format=json",
                               [event objectForKey:@"tournament"]];

        NSURL *url2 = [NSURL URLWithString:urlString];
        ASIHTTPRequest *request2 = [ASIHTTPRequest requestWithURL:url2];
        __block NSDictionary *tournamentDict;
        [request2 setCompletionBlock:^{
            NSString *responseString = [request2 responseString];
            tournamentDict = [responseString JSONValue];
            self.tournamentString = [tournamentDict objectForKey:@"tournament"]; 
        }];
        [request2 startAsynchronous];

        /* end experimental code */
        NSLog(@"%@", self.tournamentString);
        [mutableArray addObject:event];
    }
    self.eventsArray = mutableArray;
    [MBProgressHUD hideHUDForView:self.view animated:YES];

    [self.tableView reloadData];
}];