在 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助手提供,问题来源于学员提问




