pmerino
pmerino

Reputation: 6130

NSInteger always zero

I have a NSInteger which always returns zero :( I have it declared like:

NSInteger level;
@property(nonatomic, assign) NSInteger level;

The synthetize:

@synthesize fileName, filePath, theActualIndexPath, titleBar, level;

Then when using NSLog(@"%d", level) always returns 0, even after

level++; 

Or

level += 1;

What I'm doing wrong? I'm 100% sure of adding 1 to level but can't understand what's wrong :(

EDIT:

The if statement where I use this NSInteger

if (level == 0) {
    self.navigationItem.title = @"Test";

} else {
    self.navigationItem.title = self.titleBar;

}

That always ends on the first, even after adding 1

Upvotes: 1

Views: 949

Answers (3)

john
john

Reputation: 3103

Why are you declaring level twice?

Remove this line: NSInteger level;

The first declaration of level is a globally scoped variable, the second an instance variable of the class. Depending on your scope, the level being incremented by ++level is different from the level being printed by NSLog("%d", level); and tested by if (level == 0).

EDIT

Yes. Why would you expect level to not be newly allocated if you alloc another instance of the view controller? If you want to do that then you've either got to make the variable static, which shares it among instances of the same class, or make sure you do something like this:

MyViewController *newViewController = [[MyViewController alloc] init]; // However this goes
newViewController.level = oldViewController.level; // Make sure you pass the level on

Upvotes: 1

zaph
zaph

Reputation: 112855

The variable that being changed is not the same variable being accessed (in the if statement).

In the console print the values and addresses of level both where it is being set (before and after) and where s is being accessed (in the if statement.

Upvotes: 1

Vincent Bernier
Vincent Bernier

Reputation: 8664

Try this :
in the .h

@property(nonatomic) NSInteger level; // not an object assign not needed

in the .m

@synthesize level = _level;  
self.level = self.level + 1;  // and try this

And remove the line

NSInteger level;

Is this working?

Upvotes: 0

Related Questions