I’m creating a game with Cocos2D for iPhone. The following expression appears in a few places around the code:
CGFloat screenCenter = [CCDirector sharedDirector].winSize.width / 2.0;
I’d like to put this in a constants file or similar such that the expression isn’t repeated all over the place. One idea is to put
#define SCREEN_CENTER [CCDirector sharedDirector].winSize.width / 2.0
in Constants.h and just import as necessary. However I’m under the impression that it’s better style/practice in Objective-C to use static const in some capacity.
How can I declare screenCenter in just one place using static const then re-use it throughout the code as necessary?
One potential benefit of this is doing the division only once instead of every time screen center is calculated.
This is not a compile-time expression, therefore you cannot make it a
static const.If you want to keep the
#define, you need to wrap parens around it or you may introduce subtle bugs.You may also want to consider using an inline function
Or you could hang it off of
CCDirectordirectly. Assuming you don’t own that class, you can use a categoryFor added convenience you could even make it into a class method.