ZBLOG

报Reference to property 'configJsonData' in closure requires explicit use of 'self' to make capture semantics explicit

在 Swift 中,当你在闭包(closure)中引用 self 的属性或方法时,编译器要求显式使用 self 来表明你的意图,这样可以避免潜在的内存泄漏问题。这个错误提示意味着你需要在闭包中明确地使用 self 来访问 configJsonData

假设你的代码如下:

let poseOverlays = OverlayView.poseOverlays(
    fromMultiplePoseLandmarks: poseLandmarkerResult.landmarks,
    inferredOnImageOfSize: imageSize,
    ovelayViewSize: weakSelf.overlayView.bounds.size,

    locatMinX: configJsonData?.LocationList.first?.RectPoint.first?.x ?? 0,
    locatMaxX: configJsonData?.LocationList.first?.RectPoint.last?.x ?? 0,
    locatMinY: configJsonData?.LocationList.first?.RectPoint.first?.y ?? 0,

    imageContentMode: weakSelf.overlayView.imageContentMode,
    andOrientation: UIImage.Orientation.from(deviceOrientation: UIDevice.current.orientation))

修改为显式使用 self

你可以将 configJsonData 前加上 self. 来解决这个问题:

let poseOverlays = OverlayView.poseOverlays(
    fromMultiplePoseLandmarks: poseLandmarkerResult.landmarks,
    inferredOnImageOfSize: imageSize,
    ovelayViewSize: weakSelf.overlayView.bounds.size,

    locatMinX: self.configJsonData?.LocationList.first?.RectPoint.first?.x ?? 0,
    locatMaxX: self.configJsonData?.LocationList.first?.RectPoint.last?.x ?? 0,
    locatMinY: self.configJsonData?.LocationList.first?.RectPoint.first?.y ?? 0,

    imageContentMode: weakSelf.overlayView.imageContentMode,
    andOrientation: UIImage.Orientation.from(deviceOrientation: UIDevice.current.orientation))

使用 [weak self] 捕获列表

如果你的闭包是在某个异步操作或类似场景中,你可能还想考虑使用 [weak self] 捕获列表来防止循环引用。例如,如果这个调用是在一个函数内部的闭包中,你应该这样写:

someAsyncFunction { [weak self] in
    guard let strongSelf = self else { return }

    let poseOverlays = OverlayView.poseOverlays(
        fromMultiplePoseLandmarks: poseLandmarkerResult.landmarks,
        inferredOnImageOfSize: imageSize,
        ovelayViewSize: strongSelf.overlayView.bounds.size,

        locatMinX: strongSelf.configJsonData?.LocationList.first?.RectPoint.first?.x ?? 0,
        locatMaxX: strongSelf.configJsonData?.LocationList.first?.RectPoint.last?.x ?? 0,
        locatMinY: strongSelf.configJsonData?.LocationList.first?.RectPoint.first?.y ?? 0,

        imageContentMode: strongSelf.overlayView.imageContentMode,
        andOrientation: UIImage.Orientation.from(deviceOrientation: UIDevice.current.orientation))
}

总结

  • 在使用 self 的时候要显式标记,以确保你的代码是清晰和安全的。
  • 如果在闭包里有可能引起循环引用,请考虑使用弱引用 ([weak self])。


    内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=21568

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?