将NSJSONSerialization从Swift转换为Objc C.

时间:2016-02-04 11:51:24

标签: ios objective-c swift

我正在尝试将swift代码转换为Objective C,因为swift自己处理错误,我对这里的转换感到很困惑,这是快速的代码:

  func connectionDidFinishLoading(connection: NSURLConnection){
        DictonaryData = (try! NSJSONSerialization.JSONObjectWithData(main_data, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
              main_data = NSMutableData()
        delegate!.connectionDidFinish(self.identifier)
    }
}

这里是Objective C代码

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    NSError *error = nil;

    dictonaryData = (NSDictionary*)[NSJSONSerialization JSONObjectWithData:main_data options:NSJSONReadingMutableContainers error:&error];

}

在swift代码中有代码main_data = NSMutableData() delegate!.connectionDidFinish(self.identifier) 如何将此部分转换为目标c?我对swift不熟悉。谢谢你的帮助

1 个答案:

答案 0 :(得分:1)

main_data = [NSMutableData new];
[delegate connectionDidFinish:self.identifier];

delegate!.connectionDidFinish(self.identifier)
如果connectionDidFinish没有为委托对象实现(与我的objective-c代码相同),

将崩溃。要修复崩溃,您需要将Swift实现更改为

delegate?.connectionDidFinish(self.identifier)

和objective-c:

if ([delegate respondsToSelector:@selector(connectionDidFinish:)]) {
    [delegate connectionDidFinish:self.identifier];
}