Setters and getters

The rules for accessing properties in Cocos2D-x are simple: all getters have the get prefix and all setters have the set prefix. Here’s a simple example for accessing the isTouchEnabled property on a CCLayer:

Objective C

if (self.isTouchEnabled == NO) {
	self.isTouchEnabled = YES;


if (this->getIsTouchEnabled() == false) {

Defining an array

Defining an array is simple enough:

Objective C

NSMutableArray *targetsToDelete = [[NSMutableArray alloc] init];


CCMutableArray *targetsToDelete
	= new CCMutableArray;

The C++ version does look a bit crazier, but let’s take it one step at a time:

CCMutableArray *targetsToDelete

This means “declare a new CCMutableArray that will hold CCSprite instances”. What you have between < ... > is the type of the objects that will be contained by the array. In this case our array will contain only and only CCSprite objects. In Objective C you used to store mixed objects in the same array — that doesn’t seem to be possible here.

*targetsToDelete is, obviously, the variable name of the new array.

new CCMutableArray;

new will allocate a new CCMutableArray instance in memory, similar to the alloc call in Objective C. What does this mean? That the array will need to be released from memory when we are done with it.

Iterating over an array

Iterating over an array in C++ is a significantly less aesthetically pleasing endeavor.

In a nutshell, you are going to declare an iterator and use it to go over the elements in the array. The cycle breaks when your iterator reaches the end of the array.

Objective C

for (CCSprite *target in targetsToDelete) {
	[_targets removeObject:target];


CCMutableArray::CCMutableArrayIterator *jt;
for (jt = targetsToDelete->begin(); jt != targetsToDelete->end(); jt++)
	CCSprite *target =*jt;

Synthesizing a property

The setters and getters are automatically generated in Objective C by calling @synthesize. To synthesize a property in Cocos2D-x we use a macro that does pretty much the same thing:

Let’s try a simple case where we have a private label and we want to make it a property.

Objective C

CCLabelTTF *_label;
@property (nonatomic, retain) CCLabelTTF *label;
@synthesize label = _label;


CC_SYNTHESIZE(cocos2d::CCLabelTTF, _label, Label);

The code above will generate the setLabel and getLabel methods similar to Objective C’s setLabel: and label methods. If you want to access the variable directly in the owner class you can use _label.

The CC_SYNTHESIZE macro has the following signature:
CC_SYNTHESIZE(property type, private variable name, public property name)

Share this article

Tagged on:     

2 thoughts on “iPhone Cocos2D user’s guide to Cocos2D-x (Part 2)

Leave a Reply

Your email address will not be published. Required fields are marked *