ios - 在 Objective-C block 中遇到 NSString 返回类型的问题

标签 ios objective-c objective-c-blocks afnetworking-2

<分区>

谢谢小伙伴的帮助。接下来是我的问题。我需要使用 AFNetworking,当向服务器请求请求时,服务器是响应。这个结果我需要在我的方法中返回。 AFNetworking 方法使用 block 来判断成功或失败。我想在成功或失败选项 block 中返回返回服务器字符串(操作)。

- (NSString *)executeMultipart:(NSURL *)url
{
    __block NSString *strJSON;

    [_operationManager POST:[url absoluteString]parameters:_params
  constructingBodyWithBlock:^(id<AFMultipartFormData> formData){
        [formData appendPartWithFormData:[_params objectForKey:TAG_PHOTO] name:TAG_PHOTO];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        strJSON = [operation.responseString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        return strJSON;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        strJSON = [operation.responseString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        return strJSON;
    }];
}

但显示错误:

"Incompatible block pointer types sending 'NSString *(^)(AFHTTPRequestOperation *__strong, _strong id)' to parameter of type 'void (^)(AFHTTPRequestOperation *_strong, __strong id)'"

如果我的问题很愚蠢,我很抱歉,因为我开始使用 iOS 进行开发。请帮我!!!谢谢你。

最佳答案

实际上这是异步 block ,您和方法将在 block 完全执行之前返回。 你不应该返回这个 string 你应该调用一些完成处理程序或委托(delegate)方法。 更好的做法是将完成处理程序传递给方法并在返回字符串的位置调用该完成处理程序。

你的方法应该是这样的。

- (void)executeMultipart:(NSURL *)url withCompletionHandler:(void (^)(NSString*))handler
{
    __block NSString *strJSON;

    [_operationManager POST:[url absoluteString]parameters:_params
  constructingBodyWithBlock:^(id<AFMultipartFormData> formData){
        [formData appendPartWithFormData:[_params objectForKey:TAG_PHOTO] name:TAG_PHOTO];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        strJSON = [operation.responseString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
       handler(strJSON);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        strJSON = [operation.responseString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
       handler(strJSON);
    }];
}

在你使用这个方法的类中你应该调用这个方法

[obj executeMultipart:url withCompletionHandler:^(NSString* returnString)handler{
// code here 
// do whatever you want to with return string
}];

关于ios - 在 Objective-C block 中遇到 NSString 返回类型的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21637876/

上一篇:ios - Xcode 编译器错误 : ld: library not found for -lPods

下一篇:ios - 核心数据不覆盖对象

相关文章:

ios - 抑制 Parse.com ios 通知?

ios - map 不会更新到 iOS 7 中的新位置

swift - 以下 block 属性的 swift 属性 block 声明是什么?

ios - 是否有一种现代化的方式来获取 block 的弱自引用?

objective-c - UIView animateWithDuration : animations: completion: applies transform, 没有动画

ios - 如何在单元测试中点击 UIImageView

ios - AVPlayer(和 MPMoviePlayerController)试图缓冲整个(流媒体)视频,内存不足

ios - Swift:使用闭包的枚举?

iOS - 自定义segue内存泄漏

ios - 带有自定义多边形的box2d崩溃