[英]C Array with memory problems in Objective C
我的C布爾值數組第二次運行具有該數組的Cocos2d Scene時未保持其值。 應用程序第一次啟動時,c數組可以正常工作並按預期響應,但是在取消分配場景然后重新運行之后,c數組不會保留分配給它的值。 我在下面的代碼中做錯什么了嗎?
//.h
@interface GameplayLayer : CCLayer {
bool playerLog[4];
Hero *hero;
}
//.m
@implementation
- (void)ccKeyDown:(NSEvent*)keyDownEvent{
// Get pressed key (code)
UInt16 keyCode = [keyDownEvent keyCode];
// Set pressed key to true
if (keyCode == 123) playerLog[0] = TRUE; // Left
if (keyCode == 124) playerLog[1] = TRUE; // Right
if (keyCode == 126) playerLog[2] = TRUE; // up
if (keyCode == 125) playerLog[3] = TRUE; // down
// Other keys
if (keyCode == 27) { } // Escape
}
- (void)ccKeyUp:(NSEvent*)keyUpEvent
{
UInt16 keyCode = [keyUpEvent keyCode];
// Set pressed key to true
if (keyCode == 123) playerLog[0] = FALSE; // Left
if (keyCode == 124) playerLog[1] = FALSE; // Right
if (keyCode == 126) playerLog[2] = FALSE; // up
if (keyCode == 125) playerLog[3] = FALSE; // down
// Other keys
if (keyCode == 27) { } // Escape
}
-(void)update:(ccTime)delta {
if (playerLog[0] == TRUE) {//false on the second run when key is pushed down}
無論原因為何:您都不應將游戲狀態保留在與視圖相關的類中,在本例中為CCLayer。
您應該有一個將游戲狀態分組在一起的地方,在這里查看我在共享實例上的文章: http : //www.cocoanetics.com/2009/05/the-death-of-global-variables/
我看不到init方法,您應該創建一個init方法來初始化您的ivars(尤其是playerLog[]
)和/或使其具有屬性。
-(id)init
{
if (self = [super init])
{
playerLog[0]=playerLog[1]=playerLog[2]=playerLog[3]=0;
hero=nil; // or allocate it, not clear from your ex. how u use that.
}
return self;
}
我建議您將bool playerLog[4]
轉換為NSMutableArray並使用,也可以從此鏈接嘗試
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.