0

在我的应用程序中,我使用 AFNetwork 来调用服务。这是我第一次使用 AFNetwork。当我尝试通过查看一些教程来编写代码时,我遇到了一些错误:

Incompatible block Types sending `void(^)(NSUrlRequest* _strong)…`

我的代码是

  NSString *weatherUrl = [NSString stringWithFormat:@"%@weather.php?format=json", BaseURLString];
  NSURL *url = [NSURL URLWithString:weatherUrl];
  NSURLRequest *request = [NSURLRequest requestWithURL:url];

  // 2
  AFJSONRequestOperation *operation =
  [AFJSONRequestOperation JSONRequestOperationWithRequest:request
  // 3
      success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
          self.weather  = (NSDictionary *)JSON;
          self.title = @"JSON Retrieved";
          [self.tableView reloadData];
      }
  // 4
      failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
          UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
                                                       message:[NSString stringWithFormat:@"%@",error]
                                                      delegate:nil
                                             cancelButtonTitle:@"OK" otherButtonTitles:nil];
          [av show];
      }];

  // 5
  [operation start];
4

1 回答 1

0

我认为错误消息中会有一个 to... 部分,例如不兼容的块指针类型将 --- 发送到 ----。你有剩下的信息吗?

推荐

您可以查看 Apple关于 blocks 的简短实用指南。通常,不兼容...类型错误意味着变量(在这种情况下为块)格式不正确。解决此问题的最佳方法是在不同场景中使用块,并提高您准确查看问题产生位置的能力。您提供的代码片段没有向我显示足够的信息来直接回答问题。因此,这里有一个简单的示例,说明我在执行回调时如何使用块:

Class A.h

typedef void (^CallbackBlock)();

@interface Class A : <NSObject>
@property (strong, nonatomic) CallbackBlock onSomethingHappened;
...
@end


ClassA.m

@implementation ClassA

-(void) someMethod
{
    ... (after some work done)
    self.onSomethingHappened(); //this will notify any observers 
}
...
@end

ClassB.h

#import "ClassA.h"

@interface ClassB:UIViewController
@property (strong, nonatomic)ClassA * referenceToClassA;
@end

ClassB.m

@implementation ClassB

//! Can also be some other method in the lifecycle
- (void)viewDidLoad
{
    __weak ClassB *weakSelf = self;
    self.referenceToClassA.onSomethingHappened = ^(){ [weakSelf SomeMethodWithWorkTodoAfterSomethingHappened]; };

}
...
- (void)SomeMethodWithWorkTodoAfterSomethingHappened
{
    ...do some work after receiving callback from ClassA
}

@end

样品

您可以查看以下博客文章,其中介绍了使用块进行类型转换。您的错误似乎是在抱怨该块的类型转换问题。如果您无法解决,请发布更完整的错误消息,我会再看一下。我已经包含了示例,因为它迫使我思考问题。

于 2013-12-02T12:40:58.493 回答