Why isn't my variable being assigned
Ok I think my understanding of properties in objective c may not be what I thought it was.
In my program I have a singleton that contains my class.
In my class during the init I assign a value from the singleton to my property.
I then assign a value to a property of that property.
However it does not keep the value and when I do a compare of the value in the singleton nothing has changed. What is going on here? Any ideas?
@interface MainGameLoop : NSObject {
MapData *mapData;
}
@property (retain开发者_StackOverflow社区) MapData *mapData;
-(id) init
{
self = [super init];
GlobalVariables *sharedManager = [GlobalVariables sharedManager];
self.mapData = sharedManager.mapData;
return self;
}
In a function of my class:
works:
sharedManager.mapData.currentPlayer = newCurrentPlayer;
does nothing:
self.mapData.currentPlayer == newCurrentPlayer;
self.mapData.currentPlayer == newCurrentPlayer;
Are you sure that you want two equal signs there? That statement is syntactically correct and will evaluate to either true or false.
==
is a Boolean operator, while =
is an assignment operator. Like what Dave said, if you are using an if
statement such as if (self.mapData.currentPlayer == newCurrentPlayer) {…}
, you would want to use ==
because it would evaluate to true
or false
, while =
would be used to set the value of a variable, which is what I think you are trying to do.
If it's any consolation, I've made that mistake too many times to count…
Something that I do is to use NSLog()
or printf()
to make sure that each step is working correctly.
精彩评论