开发者

Objective-C: How do you declare and retain an int?

Here's my code:

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

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

Later on, when I print it out,

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

I get:

 maxSprites = 2

And operations that require it to be 18, crash or don't work, as if it's really just 2 now.

How would that be possible? =)

APPLE + SHIFT + F reveals no other usage of the maxSprites variable.

I've looked at other code examples and often they're exposing the variable with a getter and setter, and they are also using @property. Am I missing something? I'm new to Objective-C, so I might as well just be!

EDIT: hrmph, why'd I get a -1?

Thanks, I will try to learn how to do a Watchpoint.

Until then, I would like to say that I did a APPLE + SHIFT + F for maxSprites" In Project, Textual, Contains, Ignore Case and only resulted in:

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);

2nd EDIT:

I found th开发者_如何学Ce location where it changes using a watchpoint. It changes here:

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

On this line:

[self checkMatchBarAward:spriteTypeToAdd];

Odd? That function doesn't do anything with maxSprites.

EDIT: -I'm going to make a new question now to find out why the value is changing on its own. Thank you for your help guys, great job.

New post will be taken up here: Objective-C: int value changing without cause


You don't retain an int because it's not an object. Use a watchpoint and find out when your variable is changing.


Are you sure that initVariables is called at all? Is the value always 2? Are you refering to the same variable called maxSprites? Try:

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

It's hard to believe that the content of a variable just changes.

Edit: First I thought it could be "garbage" from the stack, but then I realized, that, of course, Objective-C objects are not stored on the stack, but the heap. And the MacOS X malloc implementation "blanks" allocated memory with 0.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜