Macro definition header file

Foreword:

In work, many small partners will define some commonly used macros in the PCH file, but they are afraid that writing these simple macros will waste time, and sometimes forget how to define them? The same is true in my work. So here to share with you some commonly used macro definitions, friends you like can directly use in the project (continuous update)!
For your convenience, please click GitHub-Macro Definition Header File Download!
1. Get the 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 language) reminded, if you support horizontal screen, you can use the following macro:

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000 // 当前Xcode支持iOS8及以上

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

#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 background color

#define LRClearColor [UIColor clearColor]

5. Customize and efficient NSLog

During project development, we will add logs in many places, but we don't want to use these logs when publishing, and we can't delete them one by one, so custom logs are 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;

How to use.png

The second method of use, after defining the weak reference macro, directly type weak.png
7. Set the view rounded corners 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 from angle to radians convert from radians to angle

#define LRDegreesToRadian(x) (M_PI * (x) / 180.0)
#define LRRadianToDegrees(radian) (radian*180.0)/(M_PI)

9. Set the loading prompt box (third-party framework: Toast)

This macro definition is very easy to use, but friends need CocoaPods to import a third-party framework: Toast

The usage method is as follows:
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 loading prompt box (third-party framework: MBProgressHUD)

This macro definition is similar to the previous one, as shown below:

MBProgressHUD prompt box.png

// load

#define kShowNetworkActivityIndicator() [UIApplication sharedApplication].networkActivityIndicatorVisible = YES

// Pack up and load

#define HideNetworkActivityIndicator()      [UIApplication sharedApplication].networkActivityIndicatorVisible = NO
// 设置加载
#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 of the 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

//Get picture resources

#define kGetImage(imageName) [UIImage imageNamed:[NSString stringWithFormat:@"%@",imageName]]

12. Get the current language

#define LRCurrentLanguage ([[NSLocale preferredLanguages] objectAtIndex:0])

13. Use ARC and MRC

#if __has_feature(objc_arc)
// ARC
#else
// MRC
#endif

14. Determine the current iPhone device/system version

//Determine whether it is an iPhone

#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_IPHONE ([[[UIDevice currentDevice] model] isEqualToString:@"iPhone"])

//Determine whether it is an iPad

#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define IS_IPAD ([[[UIDevice currentDevice] model] isEqualToString:@"iPad"])

//Judge whether it is ipod

#define IS_IPOD ([[[UIDevice currentDevice] model] isEqualToString:@"iPod touch"])

// Determine whether it is iPhone 5SE

#define iPhone5SE [[UIScreen mainScreen] bounds].size.width == 320.0f && [[UIScreen mainScreen] bounds].size.height == 568.0f

// Determine whether it is iPhone 6/6s

#define iPhone6_6s [[UIScreen mainScreen] bounds].size.width == 375.0f && [[UIScreen mainScreen] bounds].size.height == 667.0f

// Determine whether it is 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 to use this method

#define IOS_SYSTEM_STRING [[UIDevice currentDevice] systemVersion]

//Judging iOS 8 or higher system version

#define IOS_VERSION_8_OR_LATER (([[[UIDevice currentDevice] systemVersion] floatValue] >=8.0)? (YES):(NO))

15. Determine whether it is a real machine or an emulator

// Determine if it is an iOS system, if it is an iOS system, both the real machine and the simulator output are YES

#if TARGET_OS_IPHONE  
#endif  

#if (TARGET_IPHONE_SIMULATOR)    
          // 在模拟器的情况下
#else
         // 在真机情况下
#endif

16. Sandbox catalog file

//Get temp

#define kPathTemp NSTemporaryDirectory()

//Get Sandbox Document

#define kPathDocument [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]

//Get Sandbox Cache

#define kPathCache [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]

17. GCD macro definition

Many friends are very annoying to write the GCD method, so it is more convenient and concise to define as a macro here! As shown below:

How to use GCD macro.png

//GCD-one-time execution

#define kDISPATCH_ONCE_BLOCK(onceBlock) static dispatch_once_t onceToken; dispatch_once(&onceToken, onceBlock);

//GCD-run on the Main thread

#define kDISPATCH_MAIN_THREAD(mainQueueBlock) dispatch_async(dispatch_get_main_queue(), mainQueueBlock);

//GCD-start asynchronous thread

#define kDISPATCH_GLOBAL_QUEUE_DEFAULT(globalQueueBlock) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), globalQueueBlocl);

The use of macro and const:

Many small partners define a constant string as a macro. The most typical example is the address of the server. All the friends who use macros to define constant characters will use const to define them in the future! why? Let's take a look:

宏的用法: 一般字符串抽成宏,代码抽成宏使用。
const用法:一般常用的字符串定义成const(对于常量字符串苹果推荐我们使用const)。
宏与const区别:
1.编译时刻不同,宏属于预编译 ,const属于编译时刻
2.宏能定义代码,const不能,多个宏对于编译会相对时间较长,影响开发效率,调试过慢,const只会编译一次,缩短编译时间。
3.宏不会检查错误,const会检查错误

Through the above comparison, we will use const if we define a constant string in development, and use macros for the definition code. Let's take a look at how to use const, and enumerate the actual project usage as shown below:

Declare a constant string in FANCommonConst.h.png

Implement a constant string in FANCommonConst.m.png

In the above figure, I just simply define a few constant strings. We create a class as long as we include #import in .h and .m

Guess you like

Origin blog.csdn.net/woruosuifenglang/article/details/54929680