Game Development Reference
In-Depth Information
Naturally, your code makes assumptions about the state of the program. Assertions are
used to verify such assumptions which, if not true, would cause the app to malfunction.
The NSAssert macro and its variants NSAssert1 through NSAssert5 allow you to
write a test within your code that asserts that the given condition must be true. Otherwise,
an exception will be raised.
How is this helpful?
Imagine you have an ivar that you expect to be non- nil . This is an assumption. Should
the assumption be wrong for whatever reason, and the ivar is nil , all messages to that
object will be ignored. This obviously will affect program flow because some methods
you expect to run won't run. But it's not immediately obvious because the app doesn't
crash instantly; instead, some lines of code simply have no effect or return default values.
The earlier you can catch such a situation, the closer to the source of the problem the error
is reported—and the easier it will be fixed.
Imagine you had a specific method that needs to be executed every frame, but it doesn't
seem to be working. You change the method's code, but it makes no difference. You then
decide to add NSLog statements, but they don't print. Since there are a number of
if / else statements inside this method, you eventually decide to add an NSLog at the
start or end of the function. It still won't log anything. Then you consider the calling code,
and so on and so on. Eventually, you realize the pointer to the class whose method didn't
run is nil . Sound familiar?
Tip Whenever you find and fix a bug caused by an assumption that didn't hold
true, you should add an assertion in case it happens again.
To avoid such situations, double-check such assignments with an assertion—especially, if
one of the failure points includes human error, such as making a typo. For instance, in
GameScene.m , several ivars are declared (as shown in Listing 14-6 ), which are supposed
to be assigned by editing the node's doc root var setting in SpriteBuilder. Some are ob-
tained by a call to getChildByName: , which assumes there's a node matching that
name, and maybe even assuming there is only one node with that name.
Listing 14-6 . These ivars are partially assigned by SpriteBuilder, by using
getChildByName or by other means
@implementation GameScene
Search WWH ::




Custom Search