Game Development Reference
In-Depth Information
being declared in the @implementation section of the class. Private variables are not
visible to other classes, not even subclasses.
The _playerNode is declared as CCNode , not CCSprite . This is mainly because we
don't need its sprite-specific functionality here, so it's okay to reference it by its super
class. If at a later time you need to use its CCSprite functionality, you can change the
variable definition to __weak CCSprite* _playerNode or simply cast it like so:
CCSprite* playerSprite = (CCSprite*)_playerNode;
Tip If you have little experience with Objective-C, you can get a good under-
standing of the language and object-oriented programming concepts by reading
through Apple's “Programming with Objective-C” guide: ht-
tps://developer.apple.com/library/mac/documentation/
cocoa/conceptual/ProgrammingWithObjectiveC . Apress also has
several Objective-C titles in its library at www.apress.com .
If you are an experienced programmer and you're mainly facing syntactical
squabbles, you'll find Ray Wenderlich's “Objective-C Cheat Sheet” helpful:
http://www.raywenderlich.com/4872/objective-c-cheat-
sheet-and-quick-reference .
The __weak keyword signals the compiler that this variable should not retain the object
assigned to it. If you were to send the removeFromParent message to the _player-
Node instance, it would be allowed to deallocate and the _playerNode reference
would automatically become nil , both because of the __weak keyword.
In general, it is good practice to declare object pointer ivars not created or owned by a
class as __weak . In Cocos2D specifically, you should always declare references to nodes
as __weak when the reference is either a parent (or grandparent, etc.) or a sibling of the
node. Omitting the __weak keyword creates a strong reference, and in the worst case a
retain cycle—a situation where in its simplest form, node A strongly references node B
while B also holds a strong reference to A and both never let go of each other, and there-
fore both can't deallocate. In cases where __weak is inappropriate, you'll quickly notice
it because the reference generally becomes nil earlier than expected.
Search WWH ::




Custom Search