【问题标题】:Return object from completion block in a function in Objective C [duplicate]从Objective C中函数的完成块返回对象[重复]
【发布时间】:2017-05-12 10:36:49
【问题描述】:

我有一个调用 azure REST API 的函数。

    - (void)authenticateUser:(NSString*)usernameString
passwordString: (NSString*)passwordString{
    self.client = [MSClient clientWithApplicationURLString:@"url" applicationKey:@"url"];

    [self.client invokeAPI:@"AuthenticateAndFetchData"
                      body:nil
                HTTPMethod:@"GET"
                parameters:@{ @"userid": usernameString, @"password" : passwordString }
                   headers:nil
                completion: ^(NSData *result, NSHTTPURLResponse *response, NSError *error) {
                    if(error) {
                        NSLog(@"ERROR %@", error);
                    } else {

                        NSLog(@"%@", result);
                    }
                }];

}

此代码在函数内部。我希望在result 对象中接收到的 JSON 对象作为 NSData 返回,以便我可以在其他类中使用该对象并解析数据。谁能帮我解决这个问题?

【问题讨论】:

  • 我有一个不同的问题,我想在函数外访问完成块内的结果对象。
  • 你可以为此制作模型对象,然后用对象制作 gobal 数组,并可以在整个项目中使用
  • 在完成块内放置一个断点并检查result的值。它应该包含适当的值,如NSData。似乎是什么问题?是 nil 吗?还是从未触发完成块?您确定将完成块内的 NSData 响应值传递到您尝试打印它的位置吗?
  • @AyushOjha 为此,您需要使用您的函数制作完成处理程序,请检查此答案以使用您的函数创建完成处理程序。 stackoverflow.com/a/39138759/6433023

标签: ios objective-c json azure


【解决方案1】:
    - (void)authenticateUser:(NSString*)usernameString
passwordString: (NSString*)passwordString completeBlock:(void(^)(NSData *)) completeBlock
    {
        [self.client invokeAPI:@"fetchdata"
                          body:nil
                    HTTPMethod:@"GET"
                    parameters:@{ @"userid": usernameString, @"password" : passwordString }
                       headers:nil
                    completion: ^(NSData *result, NSHTTPURLResponse *response, NSError *error) {
                        if(error) {
                            NSLog(@"ERROR %@", error);
                        } else {
                            printf("%s", result);

                            if(completeBlock)
                                completeBlock(result);

                        }
                    }];
    }

这样调用:

[self authenticateUser: @"username" passwordString: @"password" completeBlock:^(NSData * data){
        //do something here
    }];

你想要这个吗?

【讨论】:

  • if(completeBlock) completeBlock(result);
  • 这部分是做什么的?它是否返回对象?
  • 调用 completeBlock 并将对象作为参数传递
  • 让我编辑问题中的代码。我实际上是通过函数参数发送用户名和密码来验证用户。 usernameString 和 passwordString 是函数参数。
  • 您只需添加另一个 completeBlock 参数。这不是你需要的吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多