【OC】常用命名规范总结
文章目录
- 【OC】常用命名规范总结
-
- [1.类名(Class Name)](#1.类名(Class Name))
- [2.协议名(Protocol Name)](#2.协议名(Protocol Name))
- [3.方法名(Method Name)](#3.方法名(Method Name))
- [4.属性名(Property Name)](#4.属性名(Property Name))
- [5.局部变量/实例变量(Local / Instance Variables)](#5.局部变量/实例变量(Local / Instance Variables))
- 6.常量名(Constants))
- [7. 文件名](#7. 文件名)
- 附加建议(避免的写法)
1.类名(Class Name)
- 使用 PascalCase(大驼峰)
- 建议添加前缀(例如:自定义类用 XYZ、系统类如 NS, UI)
- 表示类的含义、用途、类型
示例:
objc
XYZLoginViewController
AppConfigManager
StudentInfoModel
2.协议名(Protocol Name)
- 一般使用类名 + 协议后缀
- 常用 "Delegate" 或 "DataSource"
示例:
objc
UITableViewDelegate
XYZNetworkManagerDelegate
3.方法名(Method Name)
- 使用 小驼峰(camelCase)
- 命名应语义清晰、读起来像句子
- 多个参数要像自然语言一样接续
示例:
objc
- (void)loadUserData;
- (BOOL)saveData:(NSData *)data toFile:(NSString *)filename;
- (void)configureCell:(UITableViewCell *)cell withIndex:(NSInteger)index;
4.属性名(Property Name)
- 也是 小驼峰
- 尽量避免下划线 _(私有变量可以例外)
- 布尔值用 is/has/can 开头
示例:
objc
@property (nonatomic, strong) NSString *userName;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, assign) BOOL isLoggedIn;
5.局部变量/实例变量(Local / Instance Variables)
- 一般小驼峰
- 如果是私有变量,可加下划线 _
示例:
objc
NSString *fileName = @"report.txt";
NSInteger _internalCounter;
6.常量名(Constants)
- 全大写,用下划线分隔
- 使用 k 前缀(Apple 不强制,但常见)
示例:
objc
#define MAX_RETRY_COUNT 5
NSString *const kAppVersionKey = @"AppVersion";
7. 文件名
- 和类名保持一致
- .h / .m 成对命名
示例:
objc
LoginViewController.h
LoginViewController.m
附加建议(避免的写法)
不推荐 | 推荐 | 原因 |
---|---|---|
btn_submit | submitButton | 不符合 OC 风格 |
setdata() | setData: | 不用小写、下划线 |
login_vc | LoginViewController | 类名需 PascalCase |
i, j 作常用变量 | index, count, row | 命名应具语义 |
temp1, temp2 | currentUser, newUser | 命名应具语义、职责清晰 |