0

我正在尝试访问方法块,但我不知道如何:

__block NSString *username;
PFUser *user = [[self.messageData objectAtIndex:indexPath.row] objectForKey:@"author"];
[user fetchIfNeededInBackgroundWithBlock:^(PFObject *object, NSError *error) {
    username = [object objectForKey:@"username"]; 
    NSLog(@"%@", username); //returns "bob";
}];
NSLog(@"%@", username); //returns null

如何从块外的代码中访问变量“用户名”?

4

4 回答 4

6

Actually you are accessing the variable username outside the block. You are getting null because the block runs in another thread and you set the value after the block finish it's execution. So, your last line has been already executed in main thread while the block was running , so it's value was not set when last line was executed.That's why you are getting null.

于 2013-10-09T05:20:50.393 回答
2

fetchIfNeededInBackgroundWithBlock是一种异步方法。这就是你最后一次NSLog返回的null原因,因为它是在username检索之前执行的。所以你想要的可能是在块内调用一些方法来确保它在你获取用户数据后执行。像这样的东西:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    MyUserCell *userCell = (MyUserCell *)[tableView dequeueReusableCellWithIdentifier:MyUserCellIdentifier];
    PFUser *user = [[self.messageData objectAtIndex:indexPath.row] objectForKey:@"author"];
    userCell.user = user;
    [user fetchIfNeededInBackgroundWithBlock:^(PFObject *object, NSError *error) {
        if (object == userCell.user && !error) {
            username = [object objectForKey:@"username"]; 
            cell.textLabel.text = userName;
        }
    }]; 
}

更新:当块tableView:cellForRowAtIndexPath:按要求在方法内部调用时,答案会更新。注意:在这里,您可能需要一个自定义单元格来存储对当前用户的引用,因为如果您正在重用您的单元格,则可能会在将同一单元格重用于不同的 indexPath 之后调用块回调(因此它将有不同的用户)。

于 2013-10-09T05:29:30.467 回答
1

我建议使用 WWDC 中介绍的 NSOperationQueue。请参阅这篇文章以供参考,它认为这会有所帮助: https ://stavash.wordpress.com/2012/12/14/advanced-issues-asynchronous-uitableviewcell-content-loading-done-right/

于 2013-10-09T07:02:55.440 回答
-2

以下是我所做的示例:尝试一下:

写在下面的导入语句

typedef double (^add_block)(double,double);

阻止 - 在视图中写入此内容确实加载

__block int bx=5;
[self exampleMethodWithBlockType:^(double a,double b){
    int ax=2;
    //bx=3;
    bx=1000;
    NSLog(@"AX = %d && BX = %d",ax,bx);
    return a+b; 
}];

NSLog(@"BX = %d",bx);

方法:

-(void)exampleMethodWithBlockType:(add_block)addFunction {
    NSLog(@"Value using block type = %0.2f",addFunction(12.4,7.8));
}
于 2013-10-09T05:25:22.310 回答