English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
많은 사람들이 매크로 사용하는 것이 편리하며 개발 효율성을 높일 수 있다는 것을 알고 있습니다. 아래는 iOS 개발 과정에서 일반적으로 사용하는 매크로를 요약했습니다. 지속적으로 추가될 예정입니다.
Objective-C
//문자열이 비어있습니까? #define kStringIsEmpty(str) ([str isKindOfClass:[NSNull class]] || str == nil || [str length] < 1 ? 예 : 아니요 ) //배열이 비어있습니까? #define kArrayIsEmpty(array) (array == nil || [array isKindOfClass:[NSNull class]] || array.count == 0) //딕셔너리가 비어있습니까? #define kDictIsEmpty(dic) (dic == nil || [dic isKindOfClass:[NSNull class]] || dic.allKeys == 0) //여부는 비어있는 객체입니까? #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)) //获取屏幕宽度与高度 #define kScreenWidth \ [[UIScreen mainScreen] respondsToSelector:@selector(nativeBounds)] ? [UIScreen mainScreen].nativeBounds.size.width/[UIScreen mainScreen].nativeScale : [UIScreen mainScreen].bounds.size.width) #define kScreenHeight \ [[UIScreen mainScreen] respondsToSelector:@selector(nativeBounds)] ? [UIScreen mainScreen].nativeBounds.size.height/[UIScreen mainScreen].nativeScale : [UIScreen mainScreen].bounds.size.height) #define kScreenSize \ [[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) //一些缩写 #define kApplication [UIApplication sharedApplication] #define kKeyWindow [UIApplication sharedApplication].keyWindow #define kAppDelegate [UIApplication sharedApplication].delegate #define kUserDefaults [NSUserDefaults standardUserDefaults] #define kNotificationCenter [NSNotificationCenter defaultCenter] //APP 버전 번호 #define kAppVersion [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] //시스템 버전 번호 #define kSystemVersion [[UIDevice currentDevice] systemVersion] //현재 언어 가져오기 #define kCurrentLanguage ([[NSLocale preferredLanguages] objectAtIndex:0]) //iPhone인지 판단 #define kISiPhone (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) //iPad인지 판단 #define kISiPad (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) //도キュ먼트 경로 가져오기 #define kDocumentPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] //템프 경로 가져오기 #define kTempPath NSTemporaryDirectory() //캐시 경로 가져오기 #define kCachePath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] //실기인지 모의기인지 판단 #if TARGET_OS_IPHONE //실기 #endif #if TARGET_IPHONE_SIMULATOR //시뮬레이터 #endif //개발 중에 출력하지만 배포할 때는 출력하지 않는 NSLog #ifdef DEBUG #define NSLog(...) NSLog(@"%s 第%d행 \n %@\n\n",__func__,__LINE__,[NSString stringWithFormat:__VA_ARGS__]) #else #define NSLog(...) #endif //색상 #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] //약 참조/강 참조 #define kWeakSelf(type) __weak typeof(type) weak##type = type; #define kStrongSelf(type) __strong typeof(type) type = weak##type; //각도에서 라디안으로 변환 #define kDegreesToRadian(x) (M_PI * (x) / 180.0) //라디안에서 각도로 변환 #define kRadianToDegrees(radian) (radian * 180.0) / (M_PI) //간격 가져오기 #define kStartTime CFAbsoluteTime start = CFAbsoluteTimeGetCurrent(); #define kEndTime NSLog(@"Time: %f", CFAbsoluteTimeGetCurrent()) - 시작)
1. 크기 클래스 매크로 정의
DimensMacros.h //상태 표 높이 #define STATUS_BAR_HEIGHT 20 //네비게이션 바 높이 #define NAVIGATION_BAR_HEIGHT 44 //상태 표 + 네비게이션 표 높이 #define STATUS_AND_NAVIGATION_HEIGHT ((STATUS_BAR_HEIGHT) + (NAVIGATION_BAR_HEIGHT)) //스크린 rect #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) //스크린 해상도 #define SCREEN_RESOLUTION (SCREEN_WIDTH * SCREEN_HEIGHT * ([UIScreen mainScreen].scale)) //광고 표 높이 #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. 캐시백 디렉토리 파일 매크로 정의
PathMacros.h //파일 디렉토리 #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.도구 클래스의 매크로
UtilsMacros.h //Log utils marco #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 //시스템 버전 유틸리티 #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) // 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]])) //도를 라디안으로 변환 #define DEGREES_TO_RADIANS(d) (d * M_PI / 180) //최소한7.0의 iOS 버전 #define iOS7_OR_LATER SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0") //최소한8.0의 iOS 버전 #define iOS8_OR_LATER SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0") //iOS6에서, 네비게이션 VC에서 view의 시작 높이 #define YH_HEIGHT (iOS7_OR_LATER ? 64:0) //시스템 타임스탑프 가져오기 #define getCurentTime [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]]
4.通知Notification 관련 매크로
NotificationMacros.h //시스템 Notification 정의 #define TNCancelFavoriteProductNotification @"TNCancelFavoriteProductNotification" //북마크 취소 시 #define TNMarkFavoriteProductNotification @"TNMarkFavoriteProductNotification" //북마크 추가 시 #define kNotficationDownloadProgressChanged @"kNotficationDownloadProgressChanged" //다운로드 진행 상황 변화 #define kNotificationPauseDownload @"kNotificationPauseDownload" //다운로드 일시 중지 #define kNotificationStartDownload @"kNotificationStartDownload" //다운로드 시작 #define kNotificationDownloadSuccess @"kNotificationDownloadSuccess" //다운로드 성공 #define kNotificationDownloadFailed @"kNotificationDownloadFailed" //다운로드 실패 #define kNotificationDownloadNewMagazine @"kNotificationDownloadNewMagazine" 서버 API 인터페이스의 매크로 APIStringMacros.h ////////////////////////////////////////////////////////////////////////////////////////////////// //인터페이스 이름 관련 #ifdef DEBUG //디버그 상태의 테스트 API #define API_BASE_URL_STRING @"http://boys.test.companydomain.com/api/" #else //릴리즈 상태의 온라인 API #define API_BASE_URL_STRING @"http://www.companydomain.com/api/" #endif //인터페이스 #define GET_CONTENT_DETAIL @"channel/getContentDetail" //콘텐츠 상세 정보(이전 및 다음 포함) #define GET_COMMENT_LIST @"comment/getCommentList" //댓글 목록 가져오기 #define COMMENT_LOGIN @"comment/login" //댓글 목록 가져오기 #define COMMENT_PUBLISH @"comment/publish" //댓글 发布 #define COMMENT_DELETE @"comment/delComment" //댓글 삭제 #define LOGINOUT @"common/logout" //로그아웃 또 다른 많은 유형의 매크로가 있습니다. 여기서는 하나하나 설명하지 않습니다. 모든 매크로와 관련된 파일 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" xcode 프로젝트의 pch 파일에서 Macros.h 파일을 가져오세요 XcodeProjectName-Prefix.pch #ifdef __OBJC__ #import <UIKit/UIKit.h> #import <Foundation/Foundation.h> #import "Macros.h" #endif
이것이 IOS에서 일반적으로 사용되는 매크로의 자료 정리입니다. 앞으로도 관련 자료를 계속 추가할 예정입니다. 감사합니다.