I came across the following code and开发者_运维知识库 am wondering what the #statement means and if there are any good places to learn how to use the syntax:
#if __IPHONE_3_0
cell.textLabel.text = [photoTitles objectAtIndex:indexPath.row];
cell.textLabel.font = [UIFont systemFontOfSize:13.0];
#else
cell.text = [photoTitles objectAtIndex:indexPath.row];
cell.font = [UIFont systemFontOfSize:13.0];
#endif
This isn't Objective-C, it's the "C preprocessor", which is basically a specialized text parsing system that is run on every source file in your project before it's actually compiled. It's the same system that processes the #import
directives.
Think of it as providing "meta" compiling for your code. In this case, there's a compiler environment variable for iPhone 3.0. If that variable is present, the first two lines of code get compiled. If not, the second two do.
Much more info is here: http://en.wikipedia.org/wiki/C_preprocessor
Those are C preprocessor directives. They allow you to change the source code of a program depending on compiler options, before the source code is compiled.
In your example, the first block of code (between #if
and #else
) is compiled in if the code is being compiled for iOS 3.0 (or later). Otherwise, the second block of code is used.
Note that this happens at compile time, NOT run time. So the above technique is more useful for code that is being used in multiple projects.
If you search for information on "preprocessor directives" you should find lots more information.
Those are compiler directives, specifically conditionals. They cause your code to be compiled differently depending on the environment at the time of compilation.
For more info on conditionals and other compiler directives, check out this page on conditionals in the C Preprocessor, which work similarly for both C and Objective-C.
Remember that these only come into play at compile time. If you compile this code in its iPhone 3.0 configuration, the program will not sense at runtime that you're running it on an iPhone 4. You will have to reconfigure the source code so that __IPHONE_3_0
isn't defined, and then compile the program again.
精彩评论