English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Resumen de las macros comunes en el desarrollo de iOS

Todos sabemos que usar macros es conveniente y puede aumentar la eficiencia de desarrollo. A continuación, se resume algunas macros comunes en el proceso de desarrollo de iOS, y se agregarán continuamente.

Objective-C

//¿La cadena está vacía?
#define kStringIsEmpty(str) ([str isKindOfClass:[NSNull class]] || str == nil || [str length] < 1 ? SI : NO )
//¿El array está vacío?
#define kArrayIsEmpty(array) (array == nil || [array isKindOfClass:[NSNull class]] || array.count == 0)
//¿El diccionario está vacío?
#define kDictIsEmpty(dic) (dic == nil || [dic isKindOfClass:[NSNull class]] || dic.allKeys == 0)
//¿Es un objeto vacío?
#define kObjectIsEmpty(_object) (_object == nil \
|| [_object isKindOfClass:[NSNull class]] \
|| ([_object respondsToSelector:@selector(length)] && [(NSData *)_object length] == 0) \
|| ([_object respondsToSelector:@selector(count)] && [(NSArray *)_object count] == 0))
//Obtener el ancho y la altura de la pantalla
#define kScreenWidth \
[[UIScreen mainScreen] respondsToSelector:@selector(nativeBounds)]63; [UIScreen mainScreen].nativeBounds.size.width/[UIScreen mainScreen].nativeScale : [UIScreen mainScreen].bounds.size.width)
#define kScreenHeight \
[[UIScreen mainScreen] respondsToSelector:@selector(nativeBounds)]63; [UIScreen mainScreen].nativeBounds.size.height/[UIScreen mainScreen].nativeScale : [UIScreen mainScreen].bounds.size.height)
#define kScreenSize \
[[UIScreen mainScreen] respondsToSelector:@selector(nativeBounds)]63; CGSizeMake([UIScreen mainScreen].nativeBounds.size.width/[UIScreen mainScreen].nativeScale,[UIScreen mainScreen].nativeBounds.size.height/[UIScreen mainScreen].nativeScale) : [UIScreen mainScreen].bounds.size)
//Algunos abreviaturas
#define kApplication [UIApplication sharedApplication]
#define kKeyWindow [UIApplication sharedApplication].keyWindow
#define kAppDelegate [UIApplication sharedApplication].delegate
#define kUserDefaults  [NSUserDefaults standardUserDefaults]
#define kNotificationCenter [NSNotificationCenter defaultCenter]
//Número de versión de la aplicación
#define kAppVersion [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]
//Número de versión del sistema
#define kSystemVersion [[UIDevice currentDevice] systemVersion]
//Obtener el idioma actual
#define kCurrentLanguage ([[NSLocale preferredLanguages] objectAtIndex:0])
//Determinar si es un iPhone
#define kISiPhone (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
//Determinar si es un iPad
#define kISiPad (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
//Obtener la ruta Document de la sandbox
#define kDocumentPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
//Obtener la ruta temp de la sandbox
#define kTempPath NSTemporaryDirectory()
//Obtener la ruta del cache de la sandbox
#define kCachePath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]
//Determinar si es un dispositivo real o un simulador
#if TARGET_OS_IPHONE
//Dispositivo real
#endif
#if TARGET_IPHONE_SIMULATOR
//Simulador
#endif
//NSLog para desarrollo, pero no para despliegue
#ifdef DEBUG
#define NSLog(...) NSLog(@"%s 第%d行 \n %@\n\n",__func__,__LINE__,[NSString stringWithFormat:__VA_ARGS__])
#else
#define NSLog(...)
#endif
//Color
#define kRGBColor(r, g, b)  [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]
#define kRGBAColor(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(r)/255.0 blue:(r)/255.0 alpha:a]
#define kRandomColor KRGBColor(arc4random_uniform(256)/255.0,arc4random_uniform(256)/255.0,arc4random_uniform(256)/255.0)
#define kColorWithHex(rgbValue) \

[UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16)) / 255.0 \

green:((float)((rgbValue & 0xFF00) >> 8)) / 255.0 \

blue:((float)(rgbValue & 0xFF)) / 255.0 alpha:1.0]
//Referencia débil/Referencia fuerte
#define kWeakSelf(type) __weak typeof(type) weak##type = type;
#define kStrongSelf(type) __strong typeof(type) type = weak##type;
//Convertir grados a radianes
#define kDegreesToRadian(x)  (M_PI * (x) / 180.0)
//Convertir radianes a grados
#define kRadianToDegrees(radian) (radian * 180.0) / (M_PI)
//Obtener un intervalo de tiempo
#define kStartTime CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
#define kEndTime NSLog(@"Time: %f", CFAbsoluteTimeGetCurrent()) - start)

1.Definición de macros para clases de dimensiones

DimensMacros.h
//Altura de la barra de estado
#define STATUS_BAR_HEIGHT 20
//Altura de la barra de navegación
#define NAVIGATION_BAR_HEIGHT 44
//Altura de la barra de estado + barra de navegación
#define STATUS_AND_NAVIGATION_HEIGHT ((STATUS_BAR_HEIGHT) + (NAVIGATION_BAR_HEIGHT))
//Rectángulo de la pantalla
#define SCREEN_RECT ([UIScreen mainScreen].bounds)
#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)
#define CONTENT_HEIGHT (SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - STATUS_BAR_HEIGHT)
//Resolución de la pantalla
#define SCREEN_RESOLUTION (SCREEN_WIDTH * SCREEN_HEIGHT * ([UIScreen mainScreen].scale))
//Altura de la barra publicitaria
#define BANNER_HEIGHT 215
#define STYLEPAGE_HEIGHT 21
#define SMALLTV_HEIGHT 77
#define SMALLTV_WIDTH 110
#define FOLLOW_HEIGHT 220
#define SUBCHANNEL_HEIGHT 62

2.Definición de macros para el directorio de sandbox de archivos

PathMacros.h
//Directorio de archivos
#define kPathTemp          NSTemporaryDirectory()
#define kPathDocument        [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
#define kPathCache         [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]
#define kPathSearch         [kPathDocument stringByAppendingPathComponent:@"Search.plist"]
#define kPathMagazine        [kPathDocument stringByAppendingPathComponent:@"Magazine"]
#define kPathDownloadedMgzs     [kPathMagazine stringByAppendingPathComponent:@"DownloadedMgz.plist"]
#define kPathDownloadURLs      [kPathMagazine stringByAppendingPathComponent:@"DownloadURLs.plist"]
#define kPathOperation       [kPathMagazine stringByAppendingPathComponent:@"Operation.plist"]
#define kPathSplashScreen      [kPathCache stringByAppendingPathComponent:@"splashScreen"]
#endif

3.Macros de la clase de herramienta

UtilsMacros.h
//Marcos de utilidad de registro
#define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#ifdef DEBUG
#define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#define DLog(...)
#endif
#ifdef DEBUG
#define ULog(...)
//#define ULog(fmt, ...) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%s\n [Line %d] ", __PRETTY_FUNCTION__, __LINE__] message:[NSString stringWithFormat:fmt, ##__VA_ARGS__] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alert show]; }
#else
#define ULog(...)
#endif
//Utilidades de versión del sistema
#define SYSTEM_VERSION_EQUAL_TO(v)         ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)       ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)         ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)   ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)
// Obtener el color RGB
#define RGBA(r,g,b,a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a]
#define RGB(r,g,b) RGBA(r,g,b,1.0f)
#define IsPortrait ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait || [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown)
#define IsNilOrNull(_ref)  (((_ref) == nil) || ([(_ref) isEqual:[NSNull null]]))
//Convertir grados a radianes
#define DEGREES_TO_RADIANS(d) (d * M_PI / 180)
//igual o mayor que7.0 versión de ios
#define iOS7_OR_LATER SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")
//igual o mayor que8.0 versión de ios
#define iOS8_OR_LATER SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")
//iOS6en ese momento, la altura de inicio de la vista en VC de navegación
#define YH_HEIGHT (iOS7_OR_LATER &63; 64:0)
//Obtener la marca de tiempo del sistema
#define getCurentTime [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]]

4.Notificación relacionada con Notification

NotificationMacros.h
//Definición de Notification del sistema
#define TNCancelFavoriteProductNotification   @"TNCancelFavoriteProductNotification"   //Al cancelar favoritos
#define TNMarkFavoriteProductNotification    @"TNMarkFavoriteProductNotification"    //Al marcar favoritos
#define kNotficationDownloadProgressChanged   @"kNotficationDownloadProgressChanged"   //Cambio de progreso de descarga
#define kNotificationPauseDownload       @"kNotificationPauseDownload"        //Descarga en pausa
#define kNotificationStartDownload       @"kNotificationStartDownload"        //Inicio de descarga
#define kNotificationDownloadSuccess      @"kNotificationDownloadSuccess"       //Descarga exitosa
#define kNotificationDownloadFailed       @"kNotificationDownloadFailed"       //Fallo de descarga
#define kNotificationDownloadNewMagazine    @"kNotificationDownloadNewMagazine"
Macros de interfaz de API del servidor
APIStringMacros.h
//////////////////////////////////////////////////////////////////////////////////////////////////
//Nombre del interfaz relacionado
#ifdef DEBUG
//API de prueba en estado de Debug
#define API_BASE_URL_STRING   @"http://boys.test.companydomain.com/api/"
#else
//API en línea en estado de Lanzamiento
#define API_BASE_URL_STRING   @"http://www.companydomain.com/api/"
#endif
//Interfaz
#define GET_CONTENT_DETAIL   @"channel/getContentDetail" //Obtener detalles del contenido (incluso el anterior y el siguiente)
#define GET_COMMENT_LIST    @"comment/getCommentList"  //Obtener lista de comentarios
#define COMMENT_LOGIN      @"comment/login"      //Obtener lista de comentarios
#define COMMENT_PUBLISH     @"comment/publish"     //Publicar comentario
#define COMMENT_DELETE     @"comment/delComment"    //Eliminar comentario
#define LOGINOUT        @"common/logout"      //Cerrar sesión
Hay muchos otros tipos de macros, no se enumeran uno por uno aquí
Crear un archivo import que contenga todas las macros relacionadas Macros.h
Macros.h
#import "UtilsMacros.h"
#import "APIStringMacros.h"
#import "DimensMacros.h"
#import "NotificationMacros.h"
#import "SharePlatformMacros.h"
#import "StringMacros.h"
#import "UserBehaviorMacros.h"
#import "PathMacros.h"
En el archivo pch del proyecto xcode, se importa el archivo Macros.h
XcodeProjectName-Prefix.pch
#ifdef __OBJC__
  #import <UIKit/UIKit.h>
  #import <Foundation/Foundation.h>
  #import "Macros.h"
#endif

Aquí está la recopilación de información de macros comunes de iOS, se continuará complementando información relevante, ¡gracias por el apoyo de todos a este sitio!

Te gustará