我通过调用创建 SKSpriteNode 子类实例的函数,从 gameScene 和其他对象制作了一堆 Sprite 。
例如,从 GameScene 中,像这样:
let sizee = CGSize(width: 100, height: 100)
let posi = CGPoint(x: 200, y: 300)
func createSprite(){
let new = Circle(color: SKColor.blue, size: sizee , position: posi)
addChild(new)
new.zPosition = 2
}
在 Circle 中,我在完成一些动画后删除了每个实例:
import SpriteKit
class Circle: SKSpriteNode {
let fade = SKAction.fadeAlpha(to: 0.5, duration: 2)
let myScale = SKAction.scaleX(to: 3, duration: 2)
let die = SKAction.removeFromParent()
override init(texture: SKTexture?, color: UIColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
}
convenience init(color: UIColor, size: CGSize, position: CGPoint) {
self.init(color: color, size: size)
self.position = position
self.run(SKAction.sequence([fade, die]))
self.run(myScale)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
这足以确保从内存中释放它们吗?
或者我是否必须做其他事情来将它们从游戏世界和内存中清除?
最佳答案
几周前 Apple 更新了这个 page :
Swift uses Automatic Reference Counting (ARC) to track and manage your app’s memory usage. In most cases, this means that memory management “just works” in Swift, and you do not need to think about memory management yourself. ARC automatically frees up the memory used by class instances when those instances are no longer needed.
Reference counting only applies to instances of classes. Structures and enumerations are value types, not reference types, and are not stored and passed by reference.
有一种方法可以防止实例取消初始化,从而造成泄漏。这称为强引用循环。看看这个answer在这里你可以详细理解我现在的意思。
查看您的代码,我会这样做:
self.run(SKAction.group([fade, myScale], completion: {
[weak self] in
guard let strongSelf = self else { return }
strongSelf.removeFromParent()
}))
关于swift - 如何从内存中清除 SKSpriteNode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40312104/