iOS开发代码规范

2018-09-25  本文已影响0人  永不止步的旅行者

版本:1.0
时间:2018年9月20日

1.命名规范

1.1. 属性、数据类型命名规范

1.1.1. 声明的属性和实例变量
控件类型 前缀 demo
UIView v__ vHome
UILabel lbl__ lblName
UIButton btn__ btnHead
UITextField txf__ txfName
UITextView txv__ txvSuggest
UIImage img__ imgHead
UIImageView imgv__ imgvHead
UIScrollView scv__ scvHome
UITableView tv__ tvHome
UITableViewCell __Cell orderCell
UICollectionView cv__ cvHome
UICollectionViewCell __Cell orderCell
UICollectionReusableView crv__ crvHeader
UISlider __Slider nightShiftSlider
UISwitch __Switch nightShiftSwitch
UIActivityIndicatorView aiv__ aivNet
UISegmentedControl __Sc optionsSc
UIProgressView pv__ pvWebContent
UIPageControl pc__ pcBanner
UIViewController vc__ vcHome
UITableViewController tvc__ tvcHome
UICollectionViewController cvc__ cvcHome
UITabBarController tbc__ tbcMain
UIDatePicker __DatePicker receiveDatePicker
UIPickerView __PickerView areaPickerView
UIebView/WKWebView wv__ wvMain
1.1.2 BOOL类型属性命名
@property (assign, getter=isEditable) BOOL editable;   
1.1.3 常量命名
代码 评价
if errorCode == 10096 ... 后续维护人员怎么可能知道10096是什么含义?改动起来也很麻烦
static NSInteger const kOverTimeErrorCode = 10096; if errorCode == kOverTimeErrorCode; 很好,kOverTimeErrorCode 常量有自身的意义,又代表了实际值10096
static NSInteger const kOverTimeErrorCode = 10096;    
  // .h
  UIKIT_EXTERN NSString *const UITableViewIndexSearch;
  // .m
  NSString *const UITableViewIndexSearch = @"_UITableViewIndexSearch";       
1.1.4 通知常量的命名
代码
NSApplicationDidBecomeActiveNotification
NSWindowDidMiniaturizeNotification
NSTextViewDidChangeSelectionNotification
NSColorPanelColorDidChangeNotification
1.1.5异常常量的命名
代码
NSColorListIOException
NSColorListNotEditableException
NSDraggingException
NSFontUnavailableException

1.2代码命名规范基础

1.2.1 一般原则

1.2.1.1 清晰性:
代码 评价
insertObject:atIndex: 很好
insert:at: 不清晰,insert 什么东西? at了什么?
removeObjectAtIndex: 很好
removeObject: 很好
remove: 不清晰,移除了什么呢?
代码 评价
destinationSelection 很好
destSel 不够清晰,不知道做什么
setBackgroundColor: 很好
setBkgdColor: 不清晰
代码 评价
sendPort 这是代表“发送到端口”(动词),还是代表“发送端口”(名词)
displayName 是“显示名字”(动词),还是“需要显示的名字”(名词)
1.2.1.2 一致性
1.2.1.3 命名中不要重复描述
代码 评价
NSString 很好
NSStringObject 重复描述了,不好
代码 评价
NSUnderlineByWordMask 很好
UIApplicationWillEnterForegroundNotification 很好

1.2.2 前缀

1.2.3 方法首字母规定

代码 评价
fileExistsAtPath:isDirectory: 很好
FileExistsAtPath:FsDirectory: 不好,跟苹果的规范不一致

1.2.4类和协议名

代码 评价
NSLocking 很好,看起来就知道是个协议
NSLock 不好,看起来感觉就是一个类

1.2.5 头文件

代码 评价
NSString.h NSString和NSMutableString都在里面
NSLock.h NSLocking协议、NSLock、NSConditionLock、NSRecursiveLock都在里面

1.3方法命名

1.3.1 通用规则

代码 评价
- (NSSize)cellSize; 很好
- (NSSize)calcCellSize; calculate没有必要
- (NSSize)getCellSize; get没有必要
代码 评价
- (void)sendAction:(SEL)aSelector toObject:(id)anObject forAllCells:(BOOL)flag; 很好
- (void)sendAction:(SEL)aSelector :(id)anObject : (BOOL)flag; 第二个和第三个参数都没有关键词,看不懂
代码 评价
- (id)viewWithTag: (NSInteger)aTag; 很好,WithTag明确描述了这个参数
- (id)taggedView:(int)aTag; 不好,:aTag之前没有描述这个参数,而是taggedView,这与aTag是不符的
代码 评价
- (instancetype)initWithFrame:(CGRect)frameRect; 原方法
- (instancetype)initWithFrame:(CGRect)frameRect name: (NSString *)name 新增了一个参数,紧跟在后面,很好
代码 评价
- (int)runModalForDirectory:(NSString *)path file:(NSString *) name types: (NSArray *)fileTypes; 很好
- (int)runModalForDirectory:(NSString *)path andFile:(NSString *)name andTypes:(NSArray *)fileTypes; and 没有必要
代码 评价
- (BOOL)openFile:(NSString *)fullPath withApplication: (NSString *)appName andDeactivate:(BOOL)flag; 这个and用来代表连个独立的操作,可以使用

1.3.2访问方法

1.3.3代理方法

代码 评价
- (BOOL)tableView:(UITableView *)tableView didSelectRowAtIndexPath: (NSIndexPath *)indexPath 以tableView开头
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 以application开头
代码 评价
- (void)applicationWillResignActive:(UIApplication *)application 以application开头,参数拼接到最后

1.3.4方法参数

1.3.5私有方法

1.4函数命名

1.4.1 当一个方法中涉及的对象始终时单例对象,或者不涉及任何对象时,请使用函数,不要使用类方法/对象方法。

1.4.2函数命名规则

代码
CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height)
NSDecimalCompact(NSDecimal *number)
代码
unsigned int NSEventMaskFromType(NSEventType type)
float NSHeight(NSRect aRect)
const char *NSGetSizeAndAlignment(const char *typePtr, unsigned int *sizep, unsigned int *alignp)

2.通用缩写

2.1苹果中常用的缩写

缩写 全写
alloc Allocate
alt Alternate
app Application
calc Calculate
dealloc Deallocate
func Function
horiz Horizontal
info Information
init Initialize
int Integer
max Maximum
min Minimum
msg Message
nib Interface Builder archive.
pboard Pasteboard
rect Rectangle
Rep Representation
temp Temporary
vert Vertical

2.2 一些比较有名气的缩写

缩写
ASCII
PDF
XML
HTML
URL
RTF
TIFF
HTTP
JPG
PNG
GIF
LZW
ROM
RGB
CMYK
MIDI
FTP

3.开发框架的一些技巧和规范

3.1 initialization类方法

3.2版本和兼容性

*当为你的类新增了一些类或者方法,通常没有必要为每个类指定版本号。可以使用 respondsToSelector: 来兼容新老版本。

4.文件规范

4.1 .h文件

4.2 .m文件

方法分类
#pragma mark - class methods
#pragma mark - life cycle methods
#pragma mark - public methods
#pragma mark - event methods
#pragma mark - update and animation UI methods
#pragma mark - sdk Delegate
#pragma mark - customDelegate method(如:#pragma mark - UITableViewDelegate method,这样cmd+左键点击UITableViewDelegate就能进入这个协议所在的文件,很方便查看)
#pragma mark - private method(私有方法)
#pragma mark - messageHandle (观察者处理)
#pragma mark - getters and setter method
#import
//系统头文件
// ViewController
// View
// ViewModel
// Model
// API
// Manager
// Category

5.其他

if (job.JobState == JobState.New
      || job.JobState == JobState.Submitted
      || job.JobState == JobState.Expired
      || (job.JobTitle && job.JobTitle.length)) {
      ...
      }
if (!user.userName) return NO;
if (!user.password) return NO;
if (!user.email) return NO;

return YES;
// 这个写法不是很好
if (!isNotMember) {...} else {...} 
// 这个写法很清晰
if (isNotMember) {...} else {...}
//这样是规范的 
NSString *name 
//以下都是不规范的 
NSString * name 
NSString* name 
NSString*name
typedef NS_ENUM(NSInteger, RWTLeftMenuTopItemType) {
  RWTLeftMenuTopItemTypeMain,
  RWTLeftMenuTopItemTypeShows,
  RWTLeftMenuTopItemTypeSchedule
};
!bValue
~iValue
++iCount
*strSource
&fSum
fWidth = 5 + 5;
fLength = fWidth * 2;
fHeight = fWidth + fLength;
for(int i = 0; i < 10; i++)

5.图片命名规范

6.工程前缀

7.Apple的代码规范

😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄
以上都是个人的总结和建议,如果有什么错误或者不合适的地方,以及需要补充的地方,请大家多多提出自己宝贵的意见和建议。
😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄

上一篇 下一篇

猜你喜欢

热点阅读