1. 判斷當前環境是ARC還是MRC
#if __has_feature(objc_arc)
// 當前的編譯器環境是ARC
#else
// 當前的編譯器環境是MRC
#endif
2. 讀取info.plist文件中的數據
方式一
// File:獲取文件的全路徑 => 文件在哪(主bundle)
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Info.plist" ofType:nil];
// 1.解析info,plist
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:filePath];
// 獲取當前的版本號
NSString *Verision = dict[@"CFBundleShortVersionString"];
上述的方式比較麻煩,系統自已為我們提供了一個方法:
// 第二種方式獲取info.plist信息
NSString * Verision = [NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
3. PCH文件
PCH文件(Precompile Prefix Header File),也就是預編譯頭文件,其作用就是,方便你一次性導入在多個文件中同時用到的頭文件、宏或者URL地址等(全局使用),可以有效的幫你節約時間,提高開發效率。但是,自從Xcode 6之后,這個文件默認就不再提供了,因為PCH文件需要提前編譯,比較耗費時間. 當然如果你還想繼續使用的話,需要手動創建并配置。
使用注意點:
- pch需要提前編譯
- 需要做一些判斷,判斷下當前有沒有c文件,如果有c,就不導入OC的語法
//判斷是否是OC環境
#ifdef __OBJC__
// 1.存放一些公用的宏
#define Height (10)
// 2.存放一些公用的頭文件
#import "UIImage+Image.h"
// 3.自定義Log(輸出日志) 因為NSLog是非常耗費性能的
#ifdef DEBUG // 調試
#define XMGLog(...) NSLog(__VA_ARGS__)
#else // 發布
#define XMGLog(...)
#endif
#endif
4. 遍歷打印所有子視圖
// 獲取子視圖
- (void)getSub:(UIView *)view andLevel:(int)level {
NSArray *subviews = [view subviews];
if ([subviews count] == 0) return;
for (UIView *subview in subviews) {
NSString *blank = @"";
for (int i = 1; i < level; i++) {
blank = [NSString stringWithFormat:@" %@", blank];
}
NSLog(@"%@%d: %@", blank, level, subview.class);
[self getSub:subview andLevel:(level+1)];
}
}
比如我們想獲取self.navigationController.navigationBar
的子視圖結構我們可以
[self getSub:self.navigationController.navigationBar andLevel:1];
打印結果:
單利模式
單例模式的作用 :可以保證在程序運行過程中,一個類只有一個實例,而且該實例易于供外界訪問,從而方便地控制了實例個數,并節約系統資源。
利用GCD實現單利模式
//.h文件
#import <Foundation/Foundation.h>
@interface Singleton : NSObject
//單例方法
+(instancetype)sharedSingleton;
@end
//.m文件
#import "Singleton.h"
@implementation Singleton
//全局變量
static id _instance = nil;
//類方法,返回一個單例對象
+(instancetype)sharedSingleton{
return [[self alloc] init];
}
//alloc內部其實就是用allocWithZone:
+(instancetype)allocWithZone:(struct _NSZone *)zone{
//只進行一次
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
return _instance;
}
//初始化方法
- (instancetype)init{
// 只進行一次
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super init];
});
return _instance;
}
//copy在底層 會調用copyWithZone:
- (id)copyWithZone:(NSZone *)zone{
return _instance;
}
+ (id)copyWithZone:(struct _NSZone *)zone{
return _instance;
}
+ (id)mutableCopyWithZone:(struct _NSZone *)zone{
return _instance;
}
- (id)mutableCopyWithZone:(NSZone *)zone{
return _instance;
}
@end