gpt4 book ai didi

swift - SpriteBuilder Swift 代码连接零引用和释放问题

转载 作者:行者123 更新时间:2023-11-30 13:37:57 27 4
gpt4 key购买 nike

我正在使用 Swift (XCode 7.2.1) 和 SpriteBuilder (1.4.9) 来创建游戏。但是,我在 CCB 文件和 Swift 类之间创建代码连接时遇到一些问题。我按照网上的教程,在SpriteBuilder中添加了一个doc root var代码连接名称,然后在类中设置相应的属性为private weak var m_myVar: MyClass! 。然而,每当我尝试访问该属性时,我都会收到 nil引用。如果我删除 weak属性,然后我可以访问该属性,但是当场景被破坏时,我会收到释放问题,例如使用 CCDirector.shareDirector().replaceScene() 导航到新场景方法。

在我的具体情况下,我有一个 MainScene在 SpriteBuilder 中,其中包含以下节点层次结构:CCNode -> CCNodeGradient -> Tile 。哪里Tile CCNode 的子类在不同的 CCB 文件中定义并具有 doc root var代码连接名称m_levelLabel ,映射到 private weak var m_levelLabel: Tile! MainScene的属性(property)类(class)。

Tile类有 2 个属性 m_background类型 CCSprite9Slicem_label类型 CCLabelTTF ,两者都映射到 private weak var Tile 中的属性 swift 级。

MainScene加载我尝试在m_levelLabel上设置一些属性使用以下代码:

internal func didLoadFromCCB() {
m_levelLabel.setValue("2");
}

Tile.setValue定义于 Tile类为:

internal func setValue(value: String) {
m_label.string = value;
}

但是当 setValue方法执行 m_label属性是 nil所以fatal error: unexpectedly found nil while unwrapping an Optional value发生。这很奇怪,因为我在 MainScene 中的代码连接很明显类(class)运行良好,因为我能够调用 m_levelLabel.setValue .

有趣的是,如果我更改 Tile 中的属性类被定义为强引用,例如:

private var m_label: CCLabelTTF!;

然后代码执行正常,并且当MainScene时标签的值被更新。负载。然而,当我尝试导航离开MainScene时,应用程序现在崩溃了。错误 malloc: *** error for object 0x7a9f3200: pointer being freed was not allocated这听起来好像在破坏 Tile 中现在的强大属性时存在问题。 MainScene 拥有的类.

这里可能发生了什么?在 Swift 中定义代码连接的正确方法是什么?注意我在控制台中没有收到有关缺少代码连接属性的警告。

此处供引用的是 MainSceneTile整个类:

Main.swift

import Foundation

internal class MainScene: CCScene {

internal func didLoadFromCCB() {
m_levelLabel.setValue("1");
m_progressLabel.setValue("0%");
}

internal func play() {
let gameplayScene: CCScene = CCBReader.loadAsScene("Gameplay/GameplayScene");
CCDirector.sharedDirector().replaceScene(gameplayScene);
}

internal func levelSelection() {
print("Pressed level selection");
}

internal func progress() {
print("Pressed progress button");
}

private weak var m_playButton: CCButton!;
private weak var m_levelSelectionButton: CCButton!;
private weak var m_progressButton: CCButton!;
private weak var m_levelLabel: Tile!;
private weak var m_progressLabel: Tile!;
}

平铺.swift

import Foundation

internal class Tile : CCNode {

internal var value: String? {
return m_label?.string;
}

internal func setValue(value: String) {
m_label.string = value;
}

private weak var m_label: CCLabelTTF!;
private weak var m_background: CCSprite9Slice!;
}

最佳答案

事实证明,为了使代码连接始终有效,它们必须具有内部可访问性,而不是私有(private)。例如。

internal weak var m_label: CCLabelTTF!;

而不是

private weak var m_label: CCLabelTTF!;

我不确定为什么 private 在某些情况下有效,但在其他情况下无效,很遗憾我无法正确封装这些数据。我猜想这要么是由于 SpriteBuilder 库中的错误,要么是由于 Swift 语言的限制。

关于swift - SpriteBuilder Swift 代码连接零引用和释放问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35879944/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com