At work, many people will define some common macros in the PCH file, but they are afraid to write these simple macros waste time, and sometimes forget how to define what to do? The same is true in my work. So here are some common macro definitions that you can use directly in your project. For your convenience, please click on GitHub – macro definition header file download!
1. Obtain the screen width and height
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREENH_HEIGHT [UIScreen mainScreen].bounds.size.heightCopy the code
2. Obtain the notification center
#define LRNotificationCenter [NSNotificationCenter defaultCenter]Copy the code
3. Set a random color
#define LRRandomColor [UIColor colorWithRed:arc4random_uniform(256)/255.0 Green :arc4random_uniform(256)/255.0 Alpha blue: arc4random_uniform (256) / 255.0:1.0]Copy the code
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]Copy the code
5. Customize efficient NSLog
During the development of the project, we will add logs in many places, but we do not want to use these logs during the release, and we cannot delete them one by one, so the custom Log is inevitable!
#ifdef DEBUG #define LRLog(...) NSLog (@ "% s \ n line % d % @ \ n \ n", __func__, __LINE__, [nsstrings stringWithFormat: __VA_ARGS__]) # else # define LRLog (...). #endifCopy the code
6. Weak/strong references
#define LRWeakSelf(type) __weak typeof(type) weak##type = type;
#define LRStrongSelf(type) __strong typeof(type) type = weak##type;Copy the code
PNG
In the second use, after defining the weak-reference macro, type weak.png
7. Set the view rounded corner and border
#define LRViewBorderRadius(View, Radius, Width, Color)\ \ [View.layer setCornerRadius:(Radius)]; \ [View.layer setMasksToBounds:YES]; \ [View.layer setBorderWidth:(Width)]; \ [View.layer setBorderColor:[Color CGColor]]Copy the code
8. Change Angle from radian to radian
#define LRDegreesToRadian(x) (M_PI * (x) / 180.0)
#define LRRadianToDegrees(radian) (radian*180.0)/(M_PI)Copy the code
9. Set up the loading prompt box (third-party frameworks:Toast)
This macro definition works fine, but you need CocoaPods to import a third-party framework: Toast
Use method as follows: LRToast(@” network load failed “);
#define LRToast(str) CSToastStyle *style = [[CSToastStyle alloc] initWithDefaultStyle]; \ [kWindow makeToast: STR duration: 0.6 the position: CSToastPositionCenter style: the 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; The \}); \Copy the code
10. Set up the loading prompt box (third-party frameworks:MBProgressHUD)
This macro definition is similar to the previous one, as shown below:
PNG MBProgressHUD prompt box
/ / load # define kShowNetworkActivityIndicator () [UIApplication sharedApplication]. NetworkActivityIndicatorVisible = YES / / Pack up load # define HideNetworkActivityIndicator () [UIApplication sharedApplication]. NetworkActivityIndicatorVisible = NO / / Set the 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]; \}]; animations:^{\ item. \ } \ } \ #define kHiddenHUDAndAvtivity kRemoveBackView; kHiddenHUD; HideNetworkActivityIndicator()Copy the code
11. Get the View’s frame/ image resource
Width #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 kGetImage(imageName) [UIImage imageNamed:[NSString stringWithFormat:@"%@",imageName]]Copy the code
Get the current language
#define LRCurrentLanguage ([[NSLocale preferredLanguages] objectAtIndex:0])Copy the code
13. Use ARC and MRC
#if __has_feature(objc_arc)
// ARC
#else
// MRC
#endifCopy the code
14. Determine the current iPhone device/system version
/ / determine whether for the iPhone # define IS_IPHONE (UI_USER_INTERFACE_IDIOM () = = UIUserInterfaceIdiomPhone) / / determine whether for the # define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) #define IS_IPOD ([[UIDevice currentDevice] model] IsEqualToString :@"iPod Touch "]) // Determine whether iPhone5SE #define iPhone5SE [[UIScreen mainScreen] bounds].size.width == 320.0f&& [[UIScreen mainScreen] bounds].size. Height == 568.0f // Check whether iPhone6 /6s #define iPhone6_6s [[UIScreen] MainScreen] bounds].size. Width == 375.0f && [[UIScreen mainScreen] bounds].size. Height == 667.0f // Check whether it is iPhone 6Plus/6sPlus #define iPhone6Plus_6sPlus [[UIScreen mainScreen] bounds].size.width == 414.0f&& [[UIScreen mainScreen] #define IOS_SYSTEM_VERSION [[[UIDevice currentDevice] systemVersion] floatValue] #define IOS_VERSION_8_OR_LATER (([[UIDevice currentDevice] systemVersion] floatValue] >=8.0)? (YES):(NO))Copy the code
15. Check whether it is a real machine or a simulator
#if TARGET_OS_IPHONE
//iPhone Device
#endif
#if TARGET_IPHONE_SIMULATOR
//iPhone Simulator
#endifCopy the code
16. Sandbox directory files
// Get temp #define kPathTemp NSTemporaryDirectory( [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] / / Cache for box # define kPathCache [NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES) firstObject]Copy the code
17.GCD macro definition
Many small partners are very tired of writing GCD method, so in this definition for macro use more convenient and concise! The diagram below:
How to use GCD macros. PNG
#define kDISPATCH_ONCE_BLOCK(onceBlock) static dispatch_once_t onceToken; dispatch_once(&onceToken, onceBlock); #define kDISPATCH_MAIN_THREAD(mainQueueBlock) dispatch_async(dispatch_get_main_queue()) mainQueueBlock); #define kDISPATCH_GLOBAL_QUEUE_DEFAULT(globalQueueBlock) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), globalQueueBlocl);Copy the code
Use of macros and const:
Many people define a constant string as a macro, the most typical example is the server address. If you use macros to define constant characters, use const characters instead. Why is that? Let’s see:
- Macro usage: general string into macro, code into macro use.
- Const usage: Commonly used strings are defined as const (Apple recommends that we use const for constant strings).
- Macros differ from const:
1. The compilation time is different. Macros belong toprecompiled
Const belongs toCompile time
2. Macros can define code, but const can’t. Multiple macros take longer to compile, resulting in slow debugging.
3. Macros do not check for errors, const does
In the future, we will use const if we define a constant string, and macro if we define code. Let’s take a look at how const is used in an actual project.
Declare a constant string in fanCommonconconst. H. PNG
Fancommonconconst. M to implement a constant string. PNG
In the image above, we simply define a few constant strings. We create a class that contains #import in.h and.m, then declare a string in.h, implement it in.m, and import the class into a PCH file.
If you like a small partner, please click a like bar, welcome to leave a message to supplement and give deficiencies!