Common macro Definition collection for IOS daily work

Source: Internet
Author: User
Tags gcd

Objective:

In the work, many small partners will be in the PCH file definition some common macros, but also afraid to write these simple macro waste of time, and sometimes forget how to define what to do? I am also in the work of the same. So here to share some common macro definitions, like the small partners can be used directly in the project (continuous update)!
For the convenience of everyone, please click on GitHub-Macro definition header file download!

    • 1. Get screen width and height
#define SCREEN_WIDTH   [UIScreen mainScreen].bounds.size.width#define SCREENH_HEIGHT [UIScreen mainScreen].bounds.size.height
    • According to a netizen (out of the language) reminder, if support horizontal screen can use the following macro:
#If __iphone_os_version_max_allowed >= 80000//current Xcode support iOS8 and above#define screen_width ([[UIScreen mainscreen] Respondstoselector: @selector (nativebounds)]?[ UIScreen mainscreen].nativebounds.size.width/[uiscreen Mainscreen].nativescale:[uiscreen MainScreen]. Bounds.size.width)#define screenh_height ([[UIScreen mainscreen] Respondstoselector: @selector (nativebounds)]?[ UIScreen mainscreen].nativebounds.size.height/[uiscreen Mainscreen].nativescale:[uiscreen MainScreen]. Bounds.size.height)#define screen_size ([[UIScreen mainscreen] Respondstoselector: @selector (nativebounds)]? Cgsizemake ([UIScreen mainscreen].nativebounds.size.width/[uiscreen mainscreen].nativescale,[uiscreen MainScreen]. Nativebounds.size.height/[uiscreen mainscreen].nativescale): [UIScreen mainscreen].bounds.size)#Else #define screen_width [UIScreen mainscreen].bounds.size.width#define screenh_height [UIScreen mainscreen].bounds.size.height#define screen_size [UIScreen mainscreen].bounds.size#endif 
    • 2. Get notification hubs
#define LRNotificationCenter [NSNotificationCenter defaultCenter]
    • 3. Set Random Colors
#define LRRandomColor [UIColor colorWithRed:arc4random_uniform(256)/255.0 green:arc4random_uniform(256)/255.0 blue:arc4random_uniform(256)/255.0 alpha:1.0]
    • 4. Set RGB color/Set RGBA color
#define LRRGBColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]#define LRRGBAColor(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(r)/255.0 blue:(r)/255.0 alpha:a]// clear背景颜色#define LRClearColor [UIColor clearColor]
    • 5. Custom high-efficiency NSLog
      • In the development of the project, we will add log in many places, but do not want to use the log when the release, we can not delete one, so the custom log is inevitable!
#ifdef DEBUG#define LRLog(...) NSLog(@"%s 第%d行 \n %@\n\n",__func__,__LINE__,[NSString stringWithFormat:__VA_ARGS__])#else#define LRLog(...)#endif
    • 6. Weak references/strong references
#define LRWeakSelf(type)  __weak typeof(type) weak##type =type;#define LRStrongSelf(type)  __strong typeof(type) type = weak##type;

    • 7. Set the view fillet and border
#define LRViewBorderRadius(View, Radius, Width, Color)\setsetsetsetBorderColor:[Color CGColor]]
    • 8. Convert radians from angle to radians
#define LRDegreesToRadian(x) (M_PI * (x) / 180.0)#define LRRadianToDegrees(radian) (radian*180.0)/(M_PI)
    • 9. Set the Load Prompt box (third-party framework: Toast)
      • This macro definition is very useful, but small partners need cocoapods to import a third-party framework: Toast

Here's how to use it:

lrtoast (@ "Network load failed");  define Lrtoast (str) Cstoaststyle *style = [ [ cstoaststyle alloc"  initwithdefaultstyle ];   [ kwindow maketoast:str duration:0.6 Position: Cstoastpositioncenter style:style ;   kwindow.userinteractionenabled = NO;   Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (0.6 * nsec_per_sec)), Dispatch_get_main_queue (), ^{   kwindow.userinteractionenabled = YES;   } ); \  
    • 10. Set the Load Prompt box (third-party framework: MBPROGRESSHUD)
      This macro definition is similar to the previous one, such as:

//Load#define kshownetworkactivityindicator () [UIApplication sharedapplication]. networkactivityindicatorvisible = YES//Close load#define hidenetworkactivityindicator () [UIApplication sharedapplication]. networkactivityindicatorvisible = NO//Set load#Define networkactivityindicatorvisible (x) [UIApplication sharedapplication]. networkactivityindicatorvisible = x#define Kwindow [uiapplication Sharedapplication].keywindow#define Kbackview for (UIView *item in kwindow.subviews) {\if(Item.tag = =10000) {[item Removefromsuperview]; UIView * Aview = [[UIView alloc] init]; Aview.frame = [UIScreen mainscreen].bounds; Aview.tag =10000; Aview.backgroundcolor = [[Uicolor blackcolor] Colorwithalphacomponent:0.3]; [Kwindow Addsubview:aview]; } }#define kshowhudandactivity Kbackview; [Mbprogresshud Showhudaddedto:kwindow animated:yes];kshownetworkactivityindicator ()#define khiddenhud [Mbprogresshud hideallhudsforview:kwindow Animated:yes]#define Kremovebackview for (UIView *item in kwindow.subviews) {\if(Item.tag = =10000) {[UIView animatewithduration:0.4animations:^{Item.alpha =0.0; } completion:^ (BOOL finished) {[item removefromsuperview];}]; } }#define khiddenhudandavtivity Kremovebackview;khiddenhud; Hidenetworkactivityindicator ()
    • 11. Get the frame/picture resource for view
//获取view的frame(不建议使用)//#define kGetViewWidth(view)  view.frame.size.width//#define kGetViewHeight(view) view.frame.size.height//#define kGetViewX(view)      view.frame.origin.x//#define kGetViewY(view)      view.frame.origin.y//获取图片资源#define kGetImage(imageName) [UIImage imageNamed:[NSString stringWithFormat:@"%@",imageName]]
    • 12. Get the current language
#defineLRCurrentLanguage ([[NSLocale preferredLanguages]objectAtIndex:0])
    • 13. Using ARC and MRC
#if __has_feature(objc_arc)// ARC#else// MRC#endif
    • 14. Determine the current iphone device/system version
//Determine if the iphone#define Is_iphone (ui_user_interface_idiom () = = Uiuserinterfaceidiomphone)//Determine if the ipad#define Is_ipad (ui_user_interface_idiom () = = Uiuserinterfaceidiompad)//Determine if it is an ipod#define is_ipod ([[[[[Uidevice Currentdevice] model] isequaltostring:@ "IPOD Touch"])//Determine if the IPhone 5SE#define iphone5se [[UIScreen mainscreen] Bounds].size.width = = 320.0f && [[UIScreen Mainscreen] Bounds].size.height = = 568.0f//Determine if the iphone 6/6s#define iphone6_6s [[UIScreen mainscreen] Bounds].size.width = = 375.0f && [[UIScreen Mainscreen] Bounds].size.height = = 667.0f//Determine if the iphone 6plus/6splus#define iphone6plus_6splus [[UIScreen mainscreen] Bounds].size.width = = 414.0f && [[UIScreen Mainscreen] Bounds].size.height = = 736.0f//Get System version#define ios_system_version [[[Uidevice Currentdevice] systemversion] Floatvalue]//To determine the system version of IOS 8 or higher#define ios_version_8_or_later ([[[[[Uidevice Currentdevice] systemversion] floatvalue] >=8.0)? (YES):(NO))
    • 15. Judging whether it is a real machine or a simulator
#if TARGET_OS_IPHONE  //iPhone Device  #endif  #if TARGET_IPHONE_SIMULATOR  //iPhone Simulator  #endif
    • 16. Sandbox catalog File
//获取temp#define kPathTemp NSTemporaryDirectory()//获取沙盒 Document#define kPathDocument [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]//获取沙盒 Cache#define kPathCache [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]
    • Macro definition for 17.GCD
      Many small partners are very annoying to write gcd method, so this definition for macro use more convenient and concise! Such as:

//GCD-one-time execution   #define  Span class= "Hljs-function" >kdispatch_once_block (onceblock) static  Dispatch _once_t Oncetoken; dispatch_once (&oncetoken, Onceblock) ; //GCD-run  on main thread  #define  kdispatch_main_thread (mainqueueblock)  dispatch_async (dispatch_get_main_queue () , Mainqueueblock) ; //gcd-Open Async thread   #define  kdispatch_global_queue_default (globalqueueblock)  dispatch_async (dispatch_get_global_queue (DISPATCH_ Queue_priority_default, 0 ) , GLOBALQUEUEBLOCL) ; 
    • Use of macros and const:

      • Many small partners define a constant string, which is defined as a macro, the most typical example being the server's address. In this case, all the small partners that define constant characters with a macro are defined with a const! Why is it? Let's see:
    • Macro usage: General string extraction macro, code to use macros.

    • Const usage: Commonly used strings are defined as const (for constant strings Apple recommends that we use const).

    • Differences between macros and const:
      • 1. The compile time is different, the macro is precompiled, the const belongs to the compile time
      • 2. Macro can define the code, const can not, multiple macros for the compilation will be relatively long, the impact of development efficiency, debugging too slow, const will only compile once, shorten the compilation time.
      • 3. Macros do not check for errors, const will check for errors
        In comparison with the above, we later in the development if the definition of a constant string is const, define the code with a macro. Let's look at how to use const to enumerate the actual project usage methods such as:

In I simply define a few constant strings, we create a class as long as it contains #import in. h and. m

Common macro Definition collection for IOS daily work

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.