Thomas Clayson
Thomas Clayson

Reputation: 29925

What overhead is there #defining objects?

We have a constants file and want to be able to whitelabel our app.

Part of the white labelling is defining images that can be swapped by our clients.

What overhead would defining all these images be?

e.g. #define kMPNavigationBarBackgroundImage [UIImage imageNamed:@"nav_bar"]

Would it be worth defining NSString constants for the image names? Or will this be ok?

Bear in mind there will be hundreds of these images, are they all going to load into memory at this point? Or is the #define just a palceholder for lines of code which won't get run until they are called?

Thanks

Upvotes: 0

Views: 60

Answers (3)

trojanfoe
trojanfoe

Reputation: 122391

Well in short, your last statement is correct; the code which forms part of the #define won't be evaluated until it's referenced in the code.

Perhaps a better approach to the issue would be to put all these Assets into a dictionary that can be optionally swapped out by "the client" if they wish. The dictionary would map the well known name to the asset filename.

The issue with using #defines is that it relies on the customer putting the right code in the definition, which is tedious and error prone, for example:

// (Missing end quote)
#define kMPNavigationBarBackgroundImage [UIImage imageNamed:@"nav_bar]

Will cause a non-obvious compilation warning.

A more elegant approach would be to provide a method (somewhere) where you simply supply the well known name:

- (UIImage *)imageWithWellKnownName:(NSString *)wellKnownName;

Which looks-up the asset filename and loads it, throwing an exception if the file could not be loaded.

Upvotes: 1

George Green
George Green

Reputation: 4905

When you use #define to define some sort of constant it is just a preprocessor directive to tell it to replace the defined text in the code. So if you use:

#define image [UIImage imageNamed:@"name"];
UIImage *myImage = image;

Then before compilation it will get changed to:

UIImage *myImage = [UIImage imageNamed:@"name"];

It just gets replaced everywhere that you use it.

Hope that helps!

:)

Upvotes: 1

guenis
guenis

Reputation: 2538

"#define" is preprocessed by the compiler, before the compilation takes on all your kMPNavigationBarBackgroundImages will be replaced by your definition. It doesn't have anything to do with runtime.

http://www.cplusplus.com/doc/tutorial/preprocessor/

Upvotes: 2

Related Questions