Skip to content

eddieh/konst

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Objective-C String Constants Best Practice

When writing code for a particular platform it is important to be mindful of idioms and best practices for that platform. Throughout Apple’s framework headers and open source code string constants are always declared and defined consistently.

Besides matching the existing style and expectations, there are practical reasons for declaring your string constants as Apple does.

  • direct pointer comparison
  • clear intent
  • documentation

Best Practice

Header

In a header file declare your string constant like this.

Implementation

In the corresponding implementation file define the constant like this.

Use

Now you can use pointer comparisons rather than using isEqual: or isEqualToString:.

Why not use #define

Preprocessor defines are great for many things, but are not great for constants. Constants should be declared as const so the intent is clear. Preprocessors defines, by default, only display a warning if redefined and can be trivially suppressed. In contrast, redefining a constant is a linker error and halts compilation.

The biggest benefit is the ability to use direct pointer comparison which is constant time rather than isEqual: or isEqualToString: which can be O(n) at worst.

About

Objective-C string constants best practice

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published