Setter Getter oddness @property
I am having a really odd problem trying to set a simple float value to 1.
My property:
{
float direction;
}
@property(nonatomic)float direction;
Which is synthesized:
@synthesize direction;
I then used the following code:
- (void)setDirection:(float)_direction {
NSLog(@"Setter called with value of %f",_direction);
self->direction = _direction;
}
For testing purposes...
When I try to change the value with this,
[[w getCharacter] setDirection:1.0f];
where [w getCharacter]
gives this:
return [[[self scene] gameLayer] player];
I get the warning, "setDirection
not defined."
If I switch to dot notation([w getCharacter].direction
), I get "confused by earlier errors, bailing out".
Here is where the weirdness starts. When I try to change the value, the debug mess开发者_如何学编程age displays _direction = 0.00000
. When I check the number later, its still 0.000. I am clearly trying to change it to 1, why is this not working?
The simplest explanation is that [w getCharacter]
doesn't return the class of object you think it does. Only the class that has direction defined for it can respond to the message. You should test this by explicitly calling it with the class it defined for.
It is possible you did not include the header that defines the method.
Two probably unrelated issues:
The self->direction
construction will work for a scalar value but it does an end run around the entire class concept. In this case just use: 'direction=_direction;` and it will set it directly.
Apple reserves all names that start with underscores for its own internal use. You should not use them because Objective-c has a global name space. It's possible that you can accidentally use an Apple variable that is defined deep within a framework. (This is why framework constants all start with NS,CF,CA etc.)
[Note: In the Comments, the author says to ignore this answer.
self.direction = 1; is syntactic sugar for
[self setDirection: 1];
when you call
-(void)setDirection:(float)_newDirection {
self.direction = _newDirection;
}
You seem to be telling the compiler or preprocessor to set up a recursive loop for you. The preprocessor (I think) changes it to this:
-(void)setDirection:(float)_newDirection {
[self setDirection: _newDirection];
}
If you call it simply
-(void)setDirection:(float)_newDirection {
direction = _newDirection;
}
the assignment should work (it worked for me just now)
精彩评论