Mobile, iPhone, Mac, Games and Coding

Objective C

Gotcha with Obj-C properties

Properties in Objective-C can be quite useful sometimes, but you have to be careful because they don’t always work how you think they should. Here is a common gotcha among people new to Obj-C and properties.

Consider we have a class called Sprite, which has a property called position.

@interface Sprite : NSObject {
  CGPoint position;
}

@property (readwrite) CGPoint position;

@end

CGPoint is a struct with 2 int variables, x and y.

Lets create one:

Sprite mySprite* = [[Sprite alloc] init];

Now consider the situation of getting and setting the position.

Getting
When you call this:

CGPoint pos = mySprite.position;

It is actually the same as:

CGPoint pos = [mySprite position];

Here its clear that pos is a copy of the position (its not a reference
to the instance variable).

Setting
When you can call:

mySprite.position = pos;

It is actually the same as:

[mySprite setPosition:pos];

OK this is probably fairly clear so far!

The Gotcha
Now this is where the issue happens.

When you call this:

mySprite.position.y = 99;

It is actually the same as this:

[mySprite position].y = 99;

In this instance, the position variable of mySprite is not changed at all.

So when using properties, try to be aware of what Objective-C is actually doing behind the scenes :)