【问题标题】:Swift dictionary doesn't want to populate from C Callback functionSwift 字典不想从 C 回调函数中填充
【发布时间】:2017-01-20 21:04:32
【问题描述】:

我正在用 Swift 编写一个 PDF 解析器,我已经达到了使用回调函数 (CGPDFDictionaryApplyFunction) 获取所有字体数据的地步,getFont 函数应该填充 PDFFontCollection 类中的字体字典。 在“getFont”回调函数中,集合变量被正确填充 - 但是当回调完成时,字体字典仍然有 0 个条目。

class PDFFontCollection{
var fonts: [AnyHashable:Any]!

init(page: CGPDFPage){
    fonts = [AnyHashable:Any]()

    let fontsdict = self.findFontDictionary(page: page)

    if(fontsdict != nil){
        CGPDFDictionaryApplyFunction(fontsdict!, self.getFont , &self.fonts)
    }
}




private var getFont: CGPDFDictionaryApplierFunction = { (key, object, info) in
    var collection = info?.assumingMemoryBound(to: [AnyHashable: Any].self).pointee

    var name = String(cString: key, encoding: String.Encoding.ascii)

    var dict: CGPDFDictionaryRef?
    if (CGPDFObjectGetValue(object, .dictionary, &dict)){
        var font = PDFFont.pdfFont(withFontDictionary: dict!)
        collection?.updateValue(font!, forKey: name!)
    }


}

【问题讨论】:

  • 已经坐了 3 个小时了... 仍然没有弄清楚是什么问题
  • 你听说过 Swift Dictionary 是一个值类型吗?
  • 是的,但 & 没有指定我通过引用传递它吗?
  • 即使通过指针访问,值类型也是值类型。假设您将一个Int 指针传递给回调,您认为原始Int 值会被修改而不写回指针吗?
  • 简单的修复可能是在与 C 交互时使用 NSDictionary

标签: ios swift callback unsafe-pointers cgpdf


【解决方案1】:

对于可能感兴趣的人,PeejWeej 是对的。您需要将fonts 声明为NSMutableDictionary 才能填充它,因为[AnyHashable:Any] 总是通过引用传递。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    相关资源
    最近更新 更多