使用Swift返回的块调用Objective-C方法会导致EXC_BAD_ACCESS

时间:2016-05-18 10:01:31

标签: ios objective-c swift block

从Singleton,我尝试调用以下代码, 退出request()方法时出现崩溃:

EXC_BAD_ACCESS 堆栈以顶部的swift_unknownRelease结束。

let userService = UserService()

userService.request(user, data: data) { (dict:[NSObject : AnyObject]!, error:NSError!) in
  if let err = error {
    log.error("Add, delete or modified request: \(err)")
  }
}

obj-c方法是:

- (void)request:(UserEntity *)userEntity data:(MyData *)data withCompletion:(void(^)(NSDictionary *dict, NSError *error))completion
{
  NSString *url = [NSString stringWithFormat:@"%@?Id=%@&ype=%@",k_SERVER_REQUES, userEntity.contactID, data];

  NSOperation *reqOp = [self requestOperationWithMethod:@"POST"
                                                       URL:url
                                             withParameter:nil
                                                   success:^(NSInteger status, NSString *message, id data) {
    NSError *error;

    if (status == 1)
    { //If no error
      User *user = [userEntity fetchUserWithoutOverwriting];
      [[NSNotificationCenter defaultCenter] postNotificationName:kNotifDataChanged object:friendModel];
    }else{
      error = [NSError errorWithDomain:@"data" code:-1 userInfo:@{@"status":[NSNumber numberWithInteger:status]}];
    }
    if (completion) completion(data, error);

  } failed:^(NSString* s) {
    if(completion) completion(nil, [NSError errorWithDomain:@"data" code:-1 userInfo:@{@"detail":s}]);
  }];

  NSOperation *refreshOp = [[FeedService new] refreshProfileOperation:userEntity.contactID.longLongValue];

  // We are using NSOperation and dependency to ensure that refreshOp is executed before followOp.
  // So that the changes in followOp doesn't get overwritten by the refreshOp

  [reqOp addDependency:refreshOp];
  [[[AFHTTPRequestOperationManager manager] operationQueue] addOperation:refreshOp];
  [[[AFHTTPRequestOperationManager manager] operationQueue] addOperation:reqOp];
}

99%的时间都在工作。但我有一个触发系统崩溃的用户,我不知道为什么,因为它似乎是相同的。

首先,如果我将呼叫更改为:

userService.request(user, data: data, withCompletion: nil) 

然后它永远不会崩溃。 因此,在退出完成块时实际发生了崩溃。

进入区块时参数的值为:

dict    [NSObject : AnyObject]! Some
error   NSError!    nil None

我想知道为什么会发生这种情况,以及为什么只有这个特定用户才会发生......

2 个答案:

答案 0 :(得分:0)

在此行的Objective-C方法中:

failed:^(NSString* s) {
    if(completion) completion(nil, [NSError errorWithDomain:@"data" code:-1 userInfo:@{@"detail":s}]);
}

您可以在其中提供空的Dictionary而不是nil

答案 1 :(得分:0)

原因是:服务器有时不会发送回字典而是字符串...... 我想我应该使用地幔或类似的东西来解析请求结果。 崩溃不是很明确,使用Address Sanitizer并没有帮我调试问题。