iOS 开发那些事 ~

Objective-C代码规范

2020-05-09  本文已影响0人  hexuren

Xcode工程

1.物理文件应该与Xcode工程文件保持同步来避免文件扩张。 即Xcode下的Group应存在对应的文件夹。代码不仅是根据类型来分组,而且还可以根据功能来分组,这样代码更加清晰。
2.代码行最多应不超过80列

代码行不超过80列.png

3.缩进统一使用4空格

4空格缩进.png

代码组织

在函数分组和protocol/delegate实现中使用#pragma mark -来分类方法。主要有:
#pragma mark - Lifecycle
- (instancetype)init{}
- (void)dealloc{}
- (void)viewDidLoad{}
- (void)viewWillAppear:(BOOL)animated{}
- (void)didReceiveMemoryWarning{}

#pragma mark - IBActions
- (IBAction)submitData:(id)sender{}

#pragma mark - Public
- (void)publicMethod{}

#pragma mark - Private
- (void)privateMethod {}

#pragma mark - UITextFieldDelegate

#pragma mark - UITableViewDataSource

#pragma mark - UITableViewDelegate

Class

类的命名应使用大驼峰命名法则, 如:HomePageViewController.h
虽然官方推荐通用的类需要添加前缀,而只在应用使用的类则不需要使用前缀, 但是为了项目的统一风格, 或者在#import的时候将项目内的类跟第三方, 系统的类区分开, 此处应都添加前缀(前缀应是本项目的2-3个大写字母)

UIApplication
AFNetworking
MKMessageViewController

错误示例

Application
afNetworking
MessageViewController

Category

Category的命名应使用前缀+扩展类名+功能描述次, 例如要扩展一个基于NSString的解析类, 文件应命名成UIColor+MCStyle.h, Category的本身命名可以书写成

@interface UIColor (MCStyle)

@end

Methods

书写规范

- (void)setExampleText:(NSString *)text image:(UIImage *)image{
    // doSomething
}
if (user.isHappy) {
    //Do something
} else {
    //Do something else
}

错误示例:

if (user.isHappy)
{
  //Do something
}
else {
  //Do something else
}

命名规范

- (void)invokeWithTarget:(id)target;
- (void)setExampleText:(NSString *)text image:(UIImage *)image;

错误示例:

- (void)invokeWith:(id)target;
- (void)setExampleText:(NSString *)text i:(UIImage *)image;
- (CGSize)cellSize;
- (BOOL)isEditing;
- (void)setEditing:(BOOL)flag;
- (BOOL)canHide;
- (void)setCanHide:(BOOL)flag;

错误示例:

- (CGSize)getCellSize;
- (NSSize)getEditing;
- (void)changeEditing:(BOOL)flag;
- (BOOL)hide;
- (void)canHide:(BOOL)flag;

方法调用

- (void)doSomethingWith:(GTMFoo *)theFoo
                   rect:(NSRect)theRect
               interval:(float)theInterval {
  ...
}

而不能

[myObject doFooWith:arg1 name:arg2  // some lines with >1 arg
              error:arg3];
[myObject doFooWith:arg1
               name:arg2 error:arg3];
[myObject doFooWith:arg1
          name:arg2  // aligning keywords instead of colons
          error:arg3];

Properties

书写规范

@property (copy, nonatomic) NSString *title;

错误示例

@property(copy, nonatomic) NSString *title;
@property (nonatomic, copy) NSString *title;
@property(copy, nonatomic) NSString*title;

此处注意, NSString应用copy声明而不是retain或者strong, 因为可能会出现误传NSMutableString导致值会被更新

命名规范

变量命名应遵循小驼峰命名方法, 并书写完整单词, IBOutlet类型变量则应包含完整控件内容

@property (copy, nonatomic) NSString *title;
@property (strong, nonatomic) UIImage *image;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;

错误示例

@property (copy, nonatomic) NSString *tle;
@property (strong, nonatomic) UIImage *img;
@property (weak, nonatomic) IBOutlet UILabel *name;

属性的访问应使用点, 而不是[]

[UIApplication sharedApplication].delegate
self.array.count

错误示例

[[UIApplication sharedApplication] delegate]
[self.array count]

若你不确认要获取的值是不是属性, 请用command+鼠标左键点击进去看

属性的使用方式

为保证代码的一致性尽可能使用私有属性, 而不是实例属性

@interface MKUtil : NSObject
@property (strong, nonatomic) NSString *utilName;
@end

错误示例

@interface MKUtil : NSObject {
  NSString *utilName;
}

私有属性的访问应该统一使用self.xxx来访问, 而不是直接访问_xxx, self.xxx才会调用get方法来获取值, 统一出口才能避免产生不必要的错误

self.tableView.tableFooterView

错误示例

_tableView.tableFooterView
常量
static NSString * const HomePageViewControllerWebsite = @"[www.baidu.com";](http://www.baidu.com/)
static CGFloat const HomePageImageThumbnailHeight = 50.0;

错误示例

#define Website @"[www.baidu.com](http://www.baidu.com/)"
#define thumbnailHeight 2
extern NSString * const NSApplicationDidBecomeActiveNotification

注意notification声明的常量一定有notification结尾, 还是那句读完名字就能马上知道这变量, 方法是做什么的, 代码自注释

枚举

枚举的声明应使用NS_ENUM语法, 而不enum, 命名规则依旧是大驼峰(这里命名我觉得也可以有下划线), 由枚举类型+具体类型单词组成,可以显式的赋值

typedef NS_ENUM(NSInteger, NSTextAlignment) {
    NSTextAlignmentLeft           = 1,
    NSTextAlignmentCenter         = 2,
    NSTextAlignmentRight          = 3,
    NSTextAlignmentJustified      = 4,
    NSTextAlignmentNatural        = 5,
};

其他

BOOL
BOOL status = YES;
if (status){
    // doSomething
}

错误示例

BOOL status = YES;
if (status == YES){
    // doSomething
}
@property (assign, getter=isEditable) BOOL editable;
单例

单例应该使用标准Objective-C语法创建

+ (instancetype)sharedInstance {
  static id sharedInstance;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
      sharedInstance = [[self alloc] init];
  });
  return sharedInstance;
}

参考

上一篇 下一篇

猜你喜欢

热点阅读