日期:2014-05-18  浏览次数:20895 次

A little difference between objective-C and Java or C#

When I start to write Apps for iOS, I found a little different difference between Objective-C and Other OO language.

?

e.g.

-(void) accelerometer:(UIAccelerometer *)accelerometer
didAccelerate:(UIAcceleration *)acceleration
{
    player.position.x += acceleration.x * 10;
    player.position = pos;
}

?

If you try to build the code above, it will get error(Error: lvalue required as left operand of assignment).We write someting like player.position.x += value won't work with Objective-C properties, The problom lies how properties work in Objective-C and also how assignment works in the C language, on which Objective-C based.

?

The statement player.position.x is actually a calll to the position getter method [player position], which means you're actually retrieving a temporary position and then trying to change the x member of the temporary CGPoint. But the temporary CGPoint would then get thrown away. The position setter [player setPosition] simply will not be called automagically. You can only assign to the player.position property directly, in the case a new CGPoint.

?

In Objective-C you’ll have to live with this unfortunate issue—and possibly change programming habits if you come from a Java, C++ or C#background.

?

So we should try the code like this:

-(void) accelerometer:(UIAccelerometer *)accelerometer
didAccelerate:(UIAcceleration *)acceleration
{
    CGPoint pos = player.position;
    pos.x += acceleration.x * 10;
    player.position = pos;
}
?

[Notes from" Learn iPhone and iPad Cocos2D Game Development"