Gorgeous # define, pre-compilation Introduction ~

Source: Internet
Author: User
Tags define definition

In general, we define a constant using # define, #define的本质是文本替换, for example, # define INT_PTR int*, when we use a int_ptr,int_ptr a, B, which is equivalent to an INT * A, A, a, b; That is, define a pointer variable A and integer variable B, which is a common scenario for # define and a place to be aware of. Below I have collected and collated the common # define, and will be updated in the future. 1, the definition of constants to define constants when it is best to start with a lowercase letter k, let people see the name, (1) Navigation bar Height: We all know the iphone vertical screen when the navigation bar height of 44, this time can define a constant to represent the height, #define Knaivgationbarheight 44 (2) Screen width height: The screen width is the iOS device hardware screen size, and Viewcontroller view is not exactly the same, #define Kscreen_width [UIScreen mainscreen]. Bounds.size.width#define Kscreen_height [UIScreen mainscreen].bounds.size.height2, Memory Managed security Release Object # define SAFE_RELEASE ( x) [x release];x=nil note end No; Colon, this statement is used at dealloc time, for example-(void) dealloc{safe_release (array); [Super Dealloc];} Why does this sentence mean safe release? When we use the Objective-c object, we must ensure that its reference count Retaincount is 0, but sometimes we can not fully guarantee that we are perfect, when the object is set to nil at dealloc time, so that the memory area of the object comrade is freed. To prevent memory leaks. 3, to determine the version of the iOS system (1) The current system version number # # kcurrentsystemversion [[[Uidevice Currentdevice] systemversion] floatvalue] (2) Determine if IOS7 or higher system version # define Ios_version_7_or_later (([[[[[[[[[]] systemversion] ([[Uidevice Currentdevice] floatvalue] >=) ? (YES):(NO)) (3) Current system language # define Kcurrentlanguage [[Nslocale preferredlanguages] objectatindex:0]4, defining commonly used colors sometimes multiple controls need to set the same color, and Uicolor's RGB notation is really a waste of time, is to use a macro to define constants, you can save a lot of code, such as the following definition of purple and dark gray, #define Kpurplecolor [Uicolor colorwithred:137.0/255 green:21.0/255 blue:89.0/255 alpha:1.0] #define Kdarkgraycolor [uicolor colorwithred:100.0/255 green:100.0/255 blue:100.0/255 alpha:1.0] At this time the control to define the background color is more convenient 5, the definition of more advanced than NSLog dlognslog convenient we brute force debugging, is the output of their own observation of the value of the variable, is defined by the macro can be NSLog package more advanced, in the project PCH file, is the following code, #define Debug_mode 1#if debug_mode#define DLog (S, ...) NSLog (@ "<%p%@:(%d) >%@", Self, [[NSString stringwithutf8string:__file__] lastpathcomponent], __line__, [ NSString stringWithFormat: (s), # #__VA_ARGS__]) #else # define DLOG (S, ...) #endif例如在ViewController中使用DLog (@ "12345"), output on the console as follows, 2014-04-18 19:33:30.377 definesample[3593:70b] < 0x8a68360 viewcontroller.m: (SI) > 12345 This information includes the memory address of the string @ "12345" &LT;0X8A68360&GT; The viewcontroller.m file contains 54 lines, and the string content is 12345. Actually look at the definition of these macros, we can understand more of the system things, such as __file__ for which file to locate, __line__ to which line to navigate. These outputs are generated when we are in the debug project;, the # define Debug_mode 1 Comment out, this time will not produce output, after all, the output is to consume CPU resources, reduce the efficiency of the app operation, although the impact is very small, but the programmer is to be fine. This manual configuration of the project method, proficiency is used can greatly improve the development efficiency. It is important to note that this macro can only use NSString as a parameter, output the contents of nsstring, for arrays, dictionaries, UI controls, and primitive type int, float, which cannot be used as its argument. However, it is not very difficult to define the required macros yourself, and to use the above types as parameters. 6, the judgment is the IPHONE real computer (Device) or simulator (Simulator) #if target_os_iphone//For the Real Machine encoding NSLog (@ "IPHONE Device"); #elif Target_iphone_ SIMULATOR//For simulator encoding NSLog (@ "IPhone SIMULATOR"); #endif有的时候模拟器和真机的性能不一样, so you can make a judgment. The above macro Target_os_iphone and Target_iphone_simulator are system defined, can be directly used, press and hold command click, you can see more information. 7, determine whether it is arc//arc#if __has_feature (OBJC_ARC)//is the ARC code #else//is a manual memory management #endif8, defined GCD background thread and the main thread//background Run # define BACK_GCD ( Block) Dispatch_async (dispatch_get_global_queue (dispatch_queue_priority_default, 0), block)//main thread run # define MAIN_GCD (block) Dispatch_async (Dispatch_get_main_queue (), block) 9, single-Class # define SYNTHESIZE_SINGLETON_FOR_CLASS (classname) static classname *shared# #classname = nil; + (classname *) shared# #classname {@synchronized (self) {if (shared# #classname = = nil) {shared# #classname = [[Self]OC] init]; }} return shared# #classname; } + (ID) Allocwithzone: (Nszone *) zone {@synchronized (self) {if (shared# #classname = = nil) {shared# #classname = [Super Al Locwithzone:zone]; return shared# #classname; }} return nil; }-(ID) Copywithzone: (Nszone *) zone {return self;} Note that this is an arc when a single class of macros, another note is that the above is the use of the ' \ ' backslash, which is a # # time to line the end of the row to add line, Otherwise it's equivalent to a string of strings. The preprocessing process scans the source code, makes a preliminary conversion, and generates a new source for the compiler. The preprocessing process can be seen before the source code is processed by the compiler. A preprocessing directive is a line of code that begins with #, #后是指令关键字, allowing any number of white-space characters to exist between the keyword and the # number. The positive line statement constitutes a preprocessing directive, which jiangzi the compiler to do some conversion of the source code before compiling, here are some common preprocessing directives, # NULL instruction, no effect # # contains a source code file # define definition macro #undef un-defined macro # # If the condition is true, compile the following code #elif if the preceding # if is not true, compile the following code #endif end an # if ... #elif条件编译块 #ifdef if a macro is already defined, compile the following code #ifndef if a macro is not defined, Compile the following code #error stop compiling and display error messages recently, when looking at the company's own packaged SDK, encountered a lot of #ifdef and #ifndef, the following I am the main distance to say this preprocessing instructions flexible use. For example, you now create a button by code, UIButton *btn = [UIButton buttonwithtype:uibuttontyperoundedrect]; Btn.frame = CGRectMake (0, 0, 100, 40); [Btn settitle:@ "button" forstate:uicontrolstatenormal]; [Btn addtarget:self Action: @selector (Btnclicked) Forcontrolevents:uicontroleventtouchupinside]; [Self.view ADDSUBVIEW:BTN]; But according to the new requirements, this button is not required to be displayed on the interface at this time, it is not possible to comment out the button-related code, which is also a good way. But I prefer to use preprocessing directives to make conditional judgments, I use two methods to illustrate, (1) The first method, define a specific macro-# Debug_showbutton 0{//Create button Object btn ...//omit several code # if Debut_showbutton//If you need to display a button, add it to the parent view [Self.view addsubview:btn]; #else//Do not add it to the parent view//[self.view addsubview:btn];# ENDIF} This time if you want to display the button object, then the # define Debug_showbutton 1, otherwise written as # define Debug_showbutton 0. (2) The second method, defines a macro with no value {#ifdef Debug_showbutton [self.view addsubview:btn]; #endif} This code means that if you define a macro Debug_showbutton, The BTN is then added to the parent view and is not added to the parent view if it is not defined. At this point, if we want to add it to the parent view, write a # define Debug_showbutton at the top of the file, yes, we can not assign the corresponding value to this macro, this code simply means defining a macro with no corresponding value. Summary: In both of these ways, I recommend the second one, because in general, we define a macro that has a corresponding value in order to use that value in code, such as # define Kstatusbarhieght 20, so that we can use Kstatusbarheight as a value in the code, and the first method defines the corresponding value of the macro Debug_showbutton, we do not use it in the code, this is not a bit wasteful Instead, using the second method to define a macro that does not have a corresponding value, it is just an identifier that looks simple. I personally more recommend the second kind! ----------------------------------Excerpt from CSDN

Gorgeous # define, Precompilation Introduction ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.