本系列博客是本人的開發(fā)筆記。為了方便討論,本人新建了一個微信群(iOS技術討論群),想要加入的,請?zhí)砑颖救宋⑿牛簔hujinhui207407,【加我前請備注:iOS 】,本人博客http://www.kyson.cn 也在不停的更新中,歡迎一起討論
在iOS質量保障工具集中我們提到了Faux Pas這款強大的工具。由于篇幅原因沒有做進一步的講解,本文將詳細描述Faux Pas給我們帶來的編碼規(guī)范的建議。
函數(shù)參數(shù)變量的值,不應該被直接修改。
錯誤:
- (void)_uploadImage:(UIImage *)image needCompress:(BOOL)compress isAvatar:(BOOL)isAvatar showLoading:(BOOL)showLoading
{
if (compress) {
// 壓縮
image = [image processImage];
}
// ......
}
正確:
- (void)_uploadImage:(UIImage *)image needCompress:(BOOL)compress isAvatar:(BOOL)isAvatar showLoading:(BOOL)showLoading
{
UIImage *imgUpload = compress ? [image processImage] : image;
// ......
}
不應該對本類的引用進行硬編碼
這樣可以在運行時,讓指定的類接受到消息。這樣可以避免未能執(zhí)行子類的方法。
錯誤:
+ (DDAppConfigManger *)defaultManger
{
static DDAppConfigManger *_manger = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (_manger == nil) {
_manger = [[DDAppConfigManger alloc] init];
}
});
return _manger;
}
正確:
+ (instancetype)defaultManger
{
static DDAppConfigManger *_manger = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (_manger == nil) {
_manger = [[self alloc] init];
}
});
return _manger;
}
三目運算符
錯誤:
NSString *cityID = ([UserAccountManger defaultManger].staffInfo.city_id ? [UserAccountManger defaultManger].staffInfo.city_id : @"0");
正確:
NSString *cityID = ([UserAccountManger defaultManger].staffInfo.city_id ? : @"0");
避免在init或者dealloc方法中調用屬性的setter方法
這樣有可能會觸發(fā)KVC的通知,破壞監(jiān)聽者數(shù)據的合法和一致性。
參考鏈接:
Don’t Use Accessor Methods in Initializer Methods and dealloc
錯誤:
- (instancetype)initWithDict:(NSDictionary *)dict
{
if (self = [super init])
{
if (dict.allKeys.count) {
self.bank_name = stringFromObject(dict, @"bankName");
}
}
return self;
}
正確:
- (instancetype)initWithDict:(NSDictionary *)dict
{
if (self = [super init])
{
if (dict.allKeys.count) {
_bank_name = stringFromObject(dict, @"bankName");
}
}
return self;
}
工程的Class Prefix設置應該填上相應的值
遵守語言習慣
因為系統(tǒng)會默認給非dynamic的屬性生成setter和getter方法,所以屬性的命名最好不要以get作為前綴。
錯誤:
/**
get 短信驗證碼
*/
@property (strong, nonatomic, readonly, nonnull) RACCommand *getVerifyCodeCommand;
正確:
/**
get 短信驗證碼
*/
@property (strong, nonatomic, readonly, nonnull) RACCommand *requestVerifyCodeCommand;
錯誤:
@interface NSObject (PropertyList)
/**
* 獲取所有屬性
*
* @return
*/
- (NSArray *)getAllProperties;
@end
正確:
@interface NSObject (PropertyList)
/**
* 獲取所有屬性
*
* @return
*/
- (NSArray *)ndd_allProperties;
@end
避免潛在的斷言邊際效應
錯誤:
NSAssert(orEmpty(self.actionAddress).length > 0, @"Invalid Request actionAddress stubRequestsPassingTest. Request actionAddress must not be nil or empty.");
正確:
NSAssert(orEmpty(_actionAddress).length > 0, @"Invalid Request actionAddress stubRequestsPassingTest. Request actionAddress must not be nil or empty.");