Anon
Anon

Reputation: 623

Any smarter way to define constants in bulk?

I want to have macros for all constant strings in the project, which I am assigned to maintain.

The format of database fields are like @"first_name", @"last_name", etc.

What I want is like follows:

#define kFirstName  @"first_name"
#define kLastName   @"last_name" // And so on.

Problem: I have over 3500 unique fields with constant strings. I want each one of them to be defined as macro.

Any smarter way to do this. I am thinking of manually copy, paste & edit each one of them.

Tagging as iOS & Objective-C, as the project itself is an iPad Application.

Upvotes: 0

Views: 65

Answers (3)

Jef
Jef

Reputation: 4728

the cleanest way is to make a pair of constants files (header and main). Create a new class (inheriting from whatever, NSObject say) call it constants. Delete the @interface and @implementation, so you have an empty header (except for #import Foundation/Foundation.h) and empty main (except for importing the header.)

then declare each in the header like this

extern NSString *const kFirstName;

and implement each (in the .m file) just like this

NSString *const kFirstName = @"Johnny";

make sure the .m file is added to your target, import the header where need be.

Upvotes: 0

nburk
nburk

Reputation: 22741

In general, defining constants like this is the way to go on iOS, so you're on the right track.

You surely won't get around typing out each of the fields at least once.

I would recommend either of two approaches:

  1. use multiple .h-files for the definition of all the constants. you can group the header files according to the definitions that they contain (e.g. all fields related to user data in UserDefinitions.h). that way you at least make sure that you don't have to import all the constants everywhere in your code. working with prefixes will also be helpful in this situation, so prefix all the Macros names with the .h-file that they contain, e.g. kUserFirstName so that you you know at first sight where this constant comes from

  2. define all your constants in one (or multiple) property lists. that makes them easy to maintain. only make sure that you don't load the property file each time you use one of the constants, but rather cache the file once its loaded for the first time.

Upvotes: 2

Wain
Wain

Reputation: 119031

When using Core Data consider using mogenerator which creates constant values for you that you can reference for all of the attribute and relationship names.

Upvotes: 0

Related Questions