【问题标题】:Problems with making a completion block [iOS]制作完成块的问题 [iOS]
【发布时间】:2015-01-28 04:06:52
【问题描述】:

我正在尝试编写一个带有返回收集数据的完成块的方法。我不确定是我做得不对还是有其他问题。

我的方法:

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

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

谢谢!

【问题讨论】:

  • 将收集到的数据返回到哪里?
  • 当你尝试调用你的方法时会发生什么?您面临什么具体问题?
  • @JoshCaswell:我希望能够从不同的文件/视图控制器调用该方法并使用该 NSDictionary 取回数据
  • @Tommy 它工作正常,只是在 NSDictionary 中没有任何数据,因为我不知道如何设置它
  • 您所包含的小sn-p 代码看起来不错,但是没有太多可继续的。您需要在块中返回一个实例化的NSDictionary 对象,例如:data(myDict)。如果您需要进一步的帮助,您必须发布更多信息。

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


【解决方案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);
}];

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多