Chuyển đến nội dung

Bài 7 · Language Basics

Constants, Enums and typedef

Learn how to define constants with const, #define and extern strings, create type-safe enums with NS_ENUM and NS_OPTIONS, and name types with typedef.

Magic numbers and repeated string literals make code fragile. A named constant says what a value means and lets you change it in one place. Objective-C offers several tools: #define macros, const variables, static constants, global string constants, and enumerations. This lesson explains when to use each, how Cocoa-style enums with NS_ENUM and NS_OPTIONS work, and how typedef creates new names for types.

const variables

A const variable cannot be modified after initialization:

OBJECTIVEC
const int kMaxPlayers = 8;
const double kTaxRate = 0.2;

Prefer const over #define for typed values: it has a type, shows in the debugger and obeys scope. Cocoa uses a leading k for constants (kMaxPlayers) or a class prefix (ABCMaxPlayers). Choose one style per project.

With pointers, the position of const matters. Read the declaration from right to left:

OBJECTIVEC
const char *a;        // pointer to const char: cannot change the characters
char *const b = buf;  // const pointer: cannot point somewhere else
const char *const c = "x";  // both fixed

File-local constants with static

To keep a constant private to one .m file, mark it static const:

OBJECTIVEC
static const NSUInteger ABCPageSize = 50;
static NSString *const ABCDefaultTitle = @"Untitled";

Notice NSString *const: the const follows the *, because it is the pointer that must not change. const NSString * would forbid mutation of the string object instead, which makes no sense for immutable strings and is a common slip.

Global (public) constants

Constants other classes should use are declared in the header with extern and defined once in the .m file:

OBJECTIVEC
// ABCNotifications.h
extern NSString *const ABCUserDidLoginNotification;

// ABCNotifications.m
NSString *const ABCUserDidLoginNotification = @"ABCUserDidLoginNotification";

Cocoa uses this pattern for notification names, dictionary keys and error domains. Compare strings with isEqualToString: anyway, but a shared constant protects you from typos and gives autocompletion. Recent Xcode versions also let you write FOUNDATION_EXPORT instead of extern, which is the portable way for C++ and Objective-C++.

#define macros

#define is a textual substitution made by the preprocessor before compilation:

OBJECTIVEC
#define MAX_RETRIES 3
#define SQUARE(x) ((x) * (x))

Macros have no type and no scope, and they can surprise you: SQUARE(i++) expands to ((i++) * (i++)). Always wrap parameters and the whole body in parentheses, and prefer const or static inline functions for anything beyond simple flags and conditional compilation.

Enumerations

An enum names a set of related integer values:

OBJECTIVEC
typedef NS_ENUM(NSInteger, ABCStatus) {
    ABCStatusDraft,       // 0
    ABCStatusPublished,   // 1
    ABCStatusArchived     // 2
};

ABCStatus status = ABCStatusPublished;

NS_ENUM(type, name) declares an enumeration with a fixed underlying type. It is better than a plain C enum because the compiler knows the size, Swift imports it as a real enum, and switch statements over it warn about missing cases. Values count up from 0 unless you assign them, and you can give explicit numbers:

OBJECTIVEC
typedef NS_ENUM(NSUInteger, ABCHTTPStatus) {
    ABCHTTPStatusOK = 200,
    ABCHTTPStatusNotFound = 404,
};

Name each case with the type name as a prefix, so cases do not collide in the global namespace.

Option sets

When values can be combined, use bit flags with NS_OPTIONS:

OBJECTIVEC
typedef NS_OPTIONS(NSUInteger, ABCAlignment) {
    ABCAlignmentLeft   = 1 << 0,
    ABCAlignmentRight  = 1 << 1,
    ABCAlignmentTop    = 1 << 2,
    ABCAlignmentBottom = 1 << 3,
};

ABCAlignment a = ABCAlignmentLeft | ABCAlignmentTop;

Each flag is a different power of two so that | combines them and & tests them, as described in Operators and Expressions.

typedef

typedef gives a new name to an existing type. It is how NSInteger and BOOL are defined, and it makes complicated declarations readable:

OBJECTIVEC
typedef unsigned long ABCIdentifier;

typedef struct {
    double x;
    double y;
} ABCPoint;

typedef void (*ABCCallback)(int result);   // function pointer type
typedef void (^ABCCompletion)(BOOL ok);    // block type

A typedef names a type without creating a new one: ABCIdentifier and unsigned long are interchangeable for the compiler. Block typedefs become very valuable in the chapter on blocks, where block syntax is hard to read without them.

Stand-in: enums and option sets

The C enum and bit flags in this program follow the same patterns. In the real language NS_ENUM expands to a C enum with an explicit type.

C Stand-in (C): enum and bit flags

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: macros versus const, and pointer const

This shows the macro double-evaluation trap and the three const pointer forms:

C Stand-in (C): macro pitfalls and const pointers

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Which should I use?

Need Use
Number or value shared in one file static const
String key or notification name used across files extern NSString *const
Named set of choices NS_ENUM
Combinable flags NS_OPTIONS
Conditional compilation, simple flags #define
Shorter or clearer name for a type typedef

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does static NSString *const kTitle = @"Home"; guarantee?

    const after the * makes the pointer constant. static limits the name to this file.
  2. 2. Why prefer NS_ENUM over a plain C enum?

    NS_ENUM specifies the integer type and gives better compiler checks and Swift bridging.
  3. 3. Which values make a correct NS_OPTIONS list?

    Each flag needs its own bit so that they can be combined with | and tested with &.
  4. 4. What is SQUARE(2 + 1) if defined as #define SQUARE(x) (x * x)?

    It expands to (2 + 1 * 2 + 1), which is 5. Parenthesize macro parameters.

Summary

  • Use static const for private constants, extern ... const for shared ones and NSString *const for string keys.
  • #define is plain text substitution: parenthesize arguments or avoid it.
  • NS_ENUM creates typed enumerations; NS_OPTIONS creates combinable bit flags.
  • typedef creates names for structs, function pointers and block types.
  • Prefix names to avoid clashes, because there are no namespaces.

Next: Pointers and Structs

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.