我正在使用Swift(XCode 7.2.1)和SpriteBuilder(1.4.9)來創建遊戲。不過,我在CCB文件和Swift類之間創建代碼連接時遇到了一些問題。我在線學習了教程,並在SpriteBuilder中添加了一個文檔根var代碼連接名稱,然後在該類中設置相應的屬性爲private weak var m_myVar: MyClass!
。然而每當我嘗試和訪問該屬性,我得到一個nil
參考。如果我從代碼連接中刪除weak
屬性,那麼我可以訪問該屬性,但是當場景被銷燬時我會收到釋放問題,例如,使用CCDirector.shareDirector().replaceScene()
方法導航到新場景。SpriteBuilder Swift代碼連接無引用和釋放問題
在我的特定情況下,我有一個SpriteBuilder與MainScene
在它下面的節點層級:CCNode
- >CCNodeGradient
- >Tile
。其中Tile
是在不同的CCB文件中定義的CCNode
的子類,並具有doc root var
代碼連接名稱m_levelLabel
,其映射到MainScene
類的private weak var m_levelLabel: Tile!
屬性。
的Tile
類有2個屬性CCSprite9Slice
類型的m_background
和CCLabelTTF
類型的m_label
,這兩者被映射到private weak var
性質在Tile
夫特類。
當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
。這很奇怪,因爲我可以打電話給m_levelLabel.setValue
,因此我的代碼連接在MainScene
類中工作得很好。
有趣的是,如果我更改Tile
類的屬性被定義爲像強引用:
private var m_label: CCLabelTTF!;
然後代碼執行精細和標籤的值是MainScene
負載時更新。然而,當我試圖從MainScene
導航離開malloc: *** error for object 0x7a9f3200: pointer being freed was not allocated
時,該應用程序現在崩潰,這聽起來像是在銷燬MainScene
所擁有的Tile
類中的強力屬性時出現問題。
這裏可能會發生什麼?什麼是在Swift中定義代碼連接的正確方法?注意控制檯中沒有收到有關缺少代碼連接屬性的警告。
僅供參考這裏是MainScene
和Tile
類的全部:
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!;
}
瓷磚。迅速
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!;
}