Common macro definitions for daily work in IOS

Source: Internet
Author: User
Tags gcd

Transferred from: Http://www.jianshu.com/p/213b3b96cafe

Objective:

In the work, many small partners will PCH define some common macros in the file, but also afraid to write these simple macro waste of time, and sometimes forget how to define how 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 >=80000Current 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
LRWeakSelf(type)  __weak typeof(type) weak##type = type;#define LRStrongSelf(type) __strong typeof(type) type = weak##type;

How to use the. png
The second method of use, after the weak reference macro is defined, knock Weak.png7 directly. Set view fillets and borders
#define LRViewBorderRadius(View, Radius, Width, Color)[View.layer setCornerRadius:(Radius)];[View.layer setMasksToBounds:YES];[View.layer setBorderWidth:(Width)];[View.layer setBorderColor:[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(@"网络加载失败");

#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:


Mbprogresshud the Hint box. png
Load#Define Kshownetworkactivityindicator () [UIApplication sharedapplication].networkactivityindicatorvisible = YESClose load#Define Hidenetworkactivityindicator () [UIApplication sharedapplication].networkactivityindicatorvisible = NOSet 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.4 animations:^{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
#define LRCurrentLanguage ([[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)#Define Is_iphone ([[[[[Uidevice Currentdevice] model] isequaltostring:@"IPhone"])Determine if the ipad#Define IS_IPAD (ui_user_interface_idiom () = = Uiuserinterfaceidiompad)#Define IS_IPAD ([[[[[Uidevice Currentdevice] model] isequaltostring:@"IPad"])Determine if the ipod#Define Is_ipod ([[[[[Uidevice Currentdevice] model] isequaltostring:@"IPod Touch"])Determine if the IPhone is 5SE#Define IPHONE5SE [[UIScreen mainscreen] Bounds].size.width = =320.0f && [[UIScreen mainscreen] Bounds].size.height = =568.0fDetermine if the iphone 6/6s#Define iphone6_6s [[UIScreen mainscreen] Bounds].size.width = =375.0f && [[UIScreen mainscreen] Bounds].size.height = =667.0fDetermine if the iphone 6plus/6splus#define Iphone6plus_6splus [[UIScreen mainscreen] Bounds].size.width = = 414.0f && [[UIScreen Mainscreen] Bounds].size.height = = 736.0f//Get the system version// This method is not particularly reliable #define ios_system_version [[[ Uidevice Currentdevice] systemversion] floatvalue]//Suggest using this method #define ios_system_string [[Uidevice Currentdevice] systemversion]//Determine IOS 8 or higher system version #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 How to use the macro. png
//GCD - 一次性执行#define kDISPATCH_ONCE_BLOCK(onceBlock) static dispatch_once_t onceToken; dispatch_once(&onceToken, onceBlock);//GCD - 在Main线程上运行#define kDISPATCH_MAIN_THREAD(mainQueueBlock) dispatch_async(dispatch_get_main_queue(), mainQueueBlock);//GCD - 开启异步线程#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. Compile time is different, the macro belongs 预编译 to, Const belongs to编译时刻
      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:


A constant string is declared in FANCommonConst.h. png
Implements a constant string in FANCOMMONCONST.M. png


In I just simply define a few constant strings, we create a class as long as the .h and .m contained in #import <Foundation/Foundation.h> can, and then the .h file declaration of a string, in the .m implementation of it, and finally put this class into the PCH file, we can play it arbitrarily!



Common macro definitions for daily work in IOS

Related Article

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.