制作完成块的问题[iOS]

时间:2014-11-29 20:10:23

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

我正在尝试使用返回收集数据的完成块对方法进行编码。我不确定我是不是做得不对或其他事情就是这个问题。

我的方法:

-(void)getAllUserDataWithUsername:(NSString *)username completion:(void (^)(NSDictionary     *))data {

我希望能够将NSDictionary设置为收到的数据,并且能够在某处调用此方法时获取该数据。

谢谢!

1 个答案:

答案 0 :(得分:1)

您的声明要更清洁,这会略有变化。 data应该是NSDictionary参数的名称,而不是完成块名称。

使用完成块声明,实现和调用方法的分步指南如下:

在实现该方法的类头中,您可以声明方法:

- (void)getAllUserDataWithUsername:(NSString *)username 
                        completion:(void (^)(NSDictionary* data))completion;

注意data是如何在块中传递的参数,completion是块的名称。

在您的课程实施中,您可以这样做:

- (void)getAllUserDataWithUsername:(NSString *)username 
                        completion:(void (^)(NSDictionary* data))completion {
    // your code to retrieve the information you need
    NSDictionary *dict = //the data you retrieved
    // call the completion block and pass the data
    completion(dict); // this will be passed back with the block to the caller
}

现在,只要您调用此方法,就可以执行以下操作:

[myClass getAllUserDataWithUsername:@"username" completion:^(NSDictionary *data) {
    // data will be `dict` from above implementation
    NSLog(@"data = %@", data);
}];

希望它有所帮助。