How to declare my very own CGRectZero like constant?

This is a newbie C/Objective-C question :-)

Let say I want a CGRectOne and a CGRectTwo constants.

How can I declare that?

Thanks, Jérémy

Answers


The other answers are fine -in some cases-.

A) declaring it static will emit a copy per translation. That is fine if it is visible to exactly one translation (i.e. its definition is in your .m/.c file). Otherwise, you end up with copies in every translation which includes/imports the header with the static definition. This can result in an inflated binary, as well as an increase to your build times.

B) const CGRect CGRectOne = {...}; will emit a symbol in the scope it is declared. if that happens to be a header visible to multiple translations you'll end up with link errors (because CGRectOne is defined multiple times -- e.g. once per .c/.m file which directly or indirectly includes the header where the constant is defined).

Now that you know the context to use those 2 declarations in, let cover the extern way. The extern way allows you to:

  • declare the constant in a header
  • use the constant in many translations
  • while emitting exactly one definition of the constant

The extern approach is ideal for reusing the constant among multiple files. Here's an example:

File.h

// the declaration in the header:
extern const CGRect CGRectOne;

File.c/m

// the definition:

#import "File.h"

const CGRect CGRectOne = { { 0.0f, 0.0f }, { 1.0f, 1.0f } };

Note: Omitting the const would just make it a global variable.


There are a couple of options. With C89,

const CGRect CGRectOne = { { 0.0f, 0.0f }, { 1.0f, 1.0f } };

With C99,

const CGRect CGRectOne = {
    .origin.x = 0.0f,
    .origin.y = 0.0f,
    .size.width = 1.0f,
    .size.height = 1.0f
};

or

const CGRect CGRectOne = {
    .origin = { .x = 0.0f, .y = 0.0f },
    .size   = { .width = 1.0f, .height = 1.0f }
};

Something like this

static CGRect CGRectOne = (CGRect){.origin.x = 1.0f, .origin.y = 1.0f, .size.width = 1.0f, .size.height = 1.0f};

The technique used here worked well for me: http://www.cocos2d-iphone.org/forum/topic/2612#post-16402

Essentially its the extern method described by Justin, but it provides a pretty full example.

Also, this answer on StackOverflow provides a good example too: Constants in Objective-C


Need Your Help

Unable to find javadoc command - maven

macos maven javadoc

I ran this command in my project directory to build and package it:

Custom view made of multiple views

android android-layout

I have a set of views I want to always use together. An example of this may be something like: