【发布时间】:2018-04-17 19:32:46
【问题描述】:
我是 Swift 新手,我在 Objective c 中有一段代码,在这段代码中,NSMUtableDictionary 作为组合处理程序块返回。
我需要在完成块中点击 API 并返回 API 响应字典。 我的代码在 Objective c 中完美运行。但是当我使用桥头从 swift 调用相同的方法时,它会导致崩溃。
我的目标 C 代码是:
MYClass.h
#import <UIKit/UIKit.h>
@interface MYClass : NSObject
typedef void(^MyCompletionHandler)(NSMutableDictionary *_Nullable);
+ (void)myMethod:(NSString*_Nullable)param ComplitionHandler:(MyCompletionHandler _Nullable)complitionHandler;
@end
MYClass.m
#import "MYClass.h"
@implementation MYClass
+ (void)myMethod:(NSString*_Nullable)param ComplitionHandler:(MyCompletionHandler _Nullable)complitionHandler {
dispatch_queue_t queue = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
/// here I've written code to hit APi and got successfull response in nsmutableDict
NSMutableDictionary *response = [[NSMutableDictionary alloc]init];
response = jSonResponse;
dispatch_async(dispatch_get_main_queue(), ^{
complitionHandler (response);
});
});
}
@end
现在,当我在我的应用程序中使用它时,如果我在 Objective C 中使用它,它运行良好,但是如果我在 Swift Bridging header 中导入这个文件,并且当我在 Swift 文件中使用它时,它会导致崩溃
在目标 C 中:
[MYClass myMethod:@”param Value” ComplitionHandler:^(NSMutableDictionary * MyResponse) {
NSLog(@"Response = %@",MyResponse);
}];
很快
MYClass.myMethod("param Value", complitionHandler: {(MyResponse: NSMutableDictionary) -> Void in
print("MyResponse = \(MyResponse)")
} as? MyCompletionHandler)
在以下行中发生快速崩溃
complitionHandler (response);
当完成块需要返回Response时
dispatch_async(dispatch_get_main_queue(), ^{
complitionHandler (response); //Thread 1: EXC_BAD_ACCESS (code=1, address=0x10)
});
谁能告诉我是什么问题以及如何解决这个问题。我需要在 swift 和 Objective c 中使用 in
【问题讨论】:
-
检查您的响应参数是否为零,我认为对 swift 的翻译不好,我认为该参数在目标 C 中应该可以为空,并且翻译为 swift 应该是
NSMutableDictionary? -
它已经可以为空了
-
请提供您正在使用的swift的完整代码
-
@ReinierMelian 是正确的。在 Swift 中,您的回复是
NSMutableDictionary? -
标签: ios objective-c swift xcode