-
-
Save gsabran/30714b7c82ad24d43fe7179d638bbe47 to your computer and use it in GitHub Desktop.
For more info, see https://github.com/gsabran/SceneKit-SpriteKit-memoryLeak
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import SpriteKit | |
import SceneKit | |
// from http://stackoverflow.com/questions/24127587/how-do-i-declare-an-array-of-weak-references-in-swift | |
class Weak<T: AnyObject> { | |
weak var value : T? | |
init (value: T) { | |
self.value = value | |
} | |
} | |
class ViewController: UIViewController { | |
/* | |
* The UI is simply a SCNView, full screen, with one button on top | |
*/ | |
@IBOutlet weak var scnView: SCNView! | |
@IBAction func buttonPressed(_ sender: AnyObject) { | |
createSKScene() | |
} | |
// keep weak references to the scene to be able to count how many are alive | |
var scenes = [Weak<SKScene>]() | |
var cubeNode: SCNNode! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// setup SceneKit scene | |
let scnScene = SCNScene() | |
scnView.scene = scnScene | |
let cameraNode = SCNNode() | |
cameraNode.camera = SCNCamera() | |
cameraNode.position = SCNVector3(x: 0, y: 0, z: 25) | |
scnScene.rootNode.addChildNode(cameraNode) | |
cubeNode = SCNNode() | |
cubeNode.geometry = SCNBox(width: 5, height: 5, length: 5, chamferRadius: 0) | |
scnScene.rootNode.addChildNode(cubeNode) | |
} | |
func createSKScene() { | |
let skScene = SKScene() | |
skScene.backgroundColor = UIColor.black | |
skScene.size = CGSize(width: 100, height: 100) | |
let skNode = SKShapeNode(rect: CGRect(x: 0, y: 0, width: 90, height: 90)) | |
skNode.fillColor = UIColor.green | |
skNode.position = CGPoint(x: 5, y: 5) | |
skScene.addChild(skNode) | |
let material = cubeNode.geometry!.firstMaterial! | |
material.diffuse.contents = skScene | |
scenes.append(Weak<SKScene>(value: skScene)) | |
print("scenes count: \(countScenesAlive())") | |
} | |
func countScenesAlive() -> Int { | |
return scenes.filter { return $0.value != nil }.count | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment