Objective-C:你如何声明和保留int?

时间:2009-12-21 06:25:21

标签: objective-c int

这是我的代码:

@interface Game : Layer // this is from cocos2d
{
   int maxSprites;
}

@implementation Game
-(void)initVariables
{
  maxSprites = 18;
}

稍后,当我打印出来时,

 NSLog(@" maxSprites = %d  ", maxSprites);

我明白了:

 maxSprites = 2

要求它为18,崩溃或不起作用的操作,好像它现在真的只有2个。

怎么可能? =)

APPLE + SHIFT + F 显示maxSprites变量没有其他用法。

我查看了其他代码示例,并且经常使用getter和setter公开变量,并且他们也在使用@property。我错过了什么吗?我是Objective-C的新手,所以我不妨这样做!

编辑: hrmph,为什么我得到-1?

谢谢,我会尝试学习如何做一个观察点。

在此之前,我想说我为maxSprites做了 APPLE + SHIFT + F “在Project,Textual,Contains中,忽略大小并且只导致:

Game.h:     int maxSprites;
Game.m:     maxSprites = 18;
Game.m:     NSLog(@" maxSprites  = %d", maxSprites);
Game.m:     NSLog(@" maxSprites  = %d", maxSprites);
Game.m:     NSLog(@"maxSprites is at %p", &maxSprites);
Game.m:     NSLog(@"maxSprites is at %p", &maxSprites);
Game.m:     NSLog(@" maxSprites  = %d", maxSprites);
Game.m:     NSLog(@" maxSprites  = %d", maxSprites);
Game.m:     NSLog(@"maxSprites is at %p", &maxSprites);
Game.m:     NSLog(@"maxSprites is at %p", &maxSprites);

第二次编辑:

我使用观察点找到了它所发生变化的位置。它在这里改变:

Expression: “*(int *) 67379960”
New Value: 2
Old  Value: 18

在这一行:

[self checkMatchBarAward:spriteTypeToAdd];

奇?该函数对maxSprites没有任何作用。

编辑: - 我现在要提出一个新问题,找出价值自身发生变化的原因。谢谢你的帮助,干得好。

这里将收集新帖子: Objective-C: int value changing without cause

2 个答案:

答案 0 :(得分:6)

您不保留int,因为它不是对象。使用观察点并找出变量何时发生变化。

答案 1 :(得分:0)

你确定会调用initVariables吗? 值总是2吗? 你是在引用名为maxSprites的同一个变量吗? 尝试:

NSLog(@"maxSprites is at %p", &maxSprites);

很难相信变量的内容会发生变化。

编辑: 首先我认为它可能是堆栈中的“垃圾”,但随后 我意识到,当然,Objective-C对象没有存储在堆栈中, 但堆。并且MacOS X malloc实现“空白”分配内存为0。