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

江枫思渺然 提交于 2019-12-24 19:54:22

问题


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 the 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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/1938513/objective-c-how-do-you-declare-and-retain-an-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!