ios - Retain cycle in SCNNode's physicsBody - Stack Overflow

admin2025-04-18  6

I have a util helper that adds physics body to a node:

  @discardableResult
  public static func addPhysicsBody(to node: SCNNode, type: SCNPhysicsBodyType) -> SCNPhysicsBody {
    // Here I use SCNPhysicsShape(node:) API
    let shape = SCNPhysicsShape(node: node)
    let body = SCNPhysicsBody(type: type, shape: shape)
    node.physicsBody = body
    return body
  }

There seems to be a retain cycle. Even if I remove the node from parent, the node is still in memory.

However, if I change the code to:

  @discardableResult
  public static func addPhysicsBody(to node: SCNNode, type: SCNPhysicsBodyType) -> SCNPhysicsBody {
    // Here I change to SCNPhysicsShape(geometry:) API
    let shape =  SCNPhysicsShape(geometry: node.geometry!)
    let body = SCNPhysicsBody(type: type, shape: shape)
    node.physicsBody = body
    return body
  }

This solves the retain cycle - after node is removed from parent, the node is not in memory anymore.

I suspect the retain cycle is caused by SCNPhysicsShape(node: node) API ((node:options:)), where the node retains physics body, which retains shape, which retains the node.

However, I feel dumbfounded that apple didn't realize such an obvious retain cycle, which makes me doubt myself. Did I use the API wrong?

转载请注明原文地址:http://anycun.com/QandA/1744938046a89746.html