幾條建議助你在iOS中書寫代碼規范
大小:0.05 MB 人氣: 2017-09-25 需要積分:1
標簽:iOS(148619)
1.精簡代碼, 返回最后一句的值,這個方法有一個優點,所有的變量都在代碼塊中,也就是只在代碼塊的區域中有效,這意味著可以減少對其他作用域的命名污染。但缺點是可讀性比較差
NSURL *url = ({ NSString *urlString = [NSString stringWithFormat:@“%@/%@”, baseURLString, endpoint];
[NSURL URLWithString:urlString];
});
2.關于編譯器:關閉警告:
#pragma clang diagnostic push
#pragma clang diagnostic ignored “-Warc-performSelector-leaks”
[myObj performSelector:mySelector withObject:name];
#pragma clang diagnostic pop
3.忽略沒用的變量
#pragma unused (foo)
明確定義錯誤和警告
#error Whoa, buddy, you need to check for zero here!
#warning Dude, don‘t compare floating point numbers like this!
4.避免循環引用
如果【block內部】使用【外部聲明的強引用】訪問【對象A】, 那么【block內部】會自動產生一個【強引用】指向【對象A】
如果【block內部】使用【外部聲明的弱引用】訪問【對象A】, 那么【block內部】會自動產生一個【弱引用】指向【對象A】
__weak typeof(self) weakSelf = self;
dispatch_block_t block = ^{
[weakSelf doSomething]; // weakSelf != nil
// preemption, weakSelf turned nil
[weakSelf doSomethingElse]; // weakSelf == nil
};
最好這樣調用:
__weak typeof(self) weakSelf = self;
myObj.myBlock = ^{
__strong typeof(self) strongSelf = weakSelf;
if (strongSelf) {
[strongSelf doSomething]; // strongSelf != nil
// preemption, strongSelf still not nil(搶占的時候,strongSelf 還是非 nil 的)
[strongSelf doSomethingElse]; // strongSelf != nil }
else { // Probably nothing.。. return;
}
};
5.宏要寫成大寫,至少要有大寫,全部小寫有時候書寫不提示參數;
6.建議書寫枚舉模仿蘋果——在列出枚舉內容的同時綁定了枚舉數據類型NSUInteger,這樣帶來的好處是增強的類型檢查和更好的代碼可讀性,示例:
// 不推薦寫法
typedef enum{
UIControlStateNormal = 0,
UIControlStateHighlighted = 1 《《 0,
UIControlStateDisabled = 1 《《 1,
} UIControlState;
// 推薦寫法
typedef NS_OPTIONS(NSUInteger, UIControlState) {
UIControlStateNormal = 0,
UIControlStateHighlighted = 1 《《 0,
UIControlStateDisabled = 1 《《 1,
};
7.建議加載xib,xib名稱用NSStringFromClass(),避免書寫錯誤
// 推薦寫法
[self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([DXRecommendTagVCell class]) bundle:nil] forCellReuseIdentifier:ID];
// 不推薦寫法
[self.tableView registerNib:[UINib nibWithNibName:@“DXRecommendTagVCell” bundle:nil] forCellReuseIdentifier:ID];
8.場景需求:在繼承中,凡是要求子類重寫父類的方法必須先調用父類的這個方法進行初始化操作;建議:父類的方法名后面加上NS_REQUIRES_SUPER; 子類重寫這個方法就會自動警告提示要調用這個super方法,示例代碼
// 注意:父類中的方法加`NS_REQUIRES_SUPER`,子類重寫才有警告提示
- (void)prepare NS_REQUIRES_SUPER;
非常好我支持^.^
(0) 0%
不好我反對
(0) 0%
下載地址
幾條建議助你在iOS中書寫代碼規范下載
相關電子資料下載
- iOS17.1可能明天發布,iOS17.1主要修復哪些問題? 377
- 華為全新鴻蒙蓄勢待發 僅支持鴻蒙內核和鴻蒙系統應用 719
- 蘋果手機系統iOS 17遭用戶質疑 731
- iPhone12輻射超標?蘋果推送iOS 17.1解決此事 750
- 傳華為囤積零部件 目標明年智能手機出貨7000萬部;消息稱 MiOS 僅限國內,小米 28208
- 蘋果推送iOS17.0.3,解決iPhone15Pro系列存在機身過熱 216
- Testin云測兼容和真機服務平臺中上線iPhone 15系列手機 208
- 利爾達推出搭載HooRiiOS的Matter模組 145
- 運放參數解析:輸入偏置電流(Ibias)和失調電流(Ios) 128
- 昆侖太科發布支持國產飛騰騰銳D2000芯片的開源BIOS固件版本 448