iOS组代码规范

2018-10-19  本文已影响38人  小岂几哥

不规范的代码,读起来身心疲惫,改起来后患无穷

iOS成员编写代码我们应该遵循以下规范:


1. 语言

首选
UIColor *myColor = [UIColor whiteColor];
不可选
UIColor *myColour = [UIColor whiteColor]; 

2. 代码组织

#pragma mark - Lifecycle
- (instancetype)init {}
- (void)dealloc {}
- (void)viewDidLoad {}
- (void)viewWillAppear:(BOOL)animated {}
- (void)didReceiveMemoryWarning {}

#pragma mark - Custom Accessors
- (void)setCustomProperty:(id)value {}
- (id)customProperty {}

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

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

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

#pragma mark - Protocol conformance
#pragma mark - UITextFieldDelegate
#pragma mark - UITableViewDataSource
#pragma mark - UITableViewDelegate

#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone {}

#pragma mark - NSObject
- (NSString *)description {}

3. 间距

首选
if (user.isHappy) {
  //Do something
} else {
  //Do something else
}
不可选
if (user.isHappy)
{
    //Do something
}
else {
    //Do something else
}

4. 注释

5. 如何命名

首选
UIButton *settingsButton;
不可选
UIButton *setBut;
首选
static NSTimeInterval const RWTTutorialViewControllerNavigationFadeAnimationDuration = 0.3;
不可选
static NSTimeInterval const fadetime = 1.7;
首选
@property (strong, nonatomic) NSString *descriptiveVariableName;
不可选
id varnm;

6. 强调

7. 方法

首选
- (void)setExampleText:(NSString *)text image:(UIImage *)image;
- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;
- (id)viewWithTag:(NSInteger)tag;
- (instancetype)initWithWidth:(CGFloat)width height:(CGFloat)height;
不可选
-(void)setT:(NSString *)text i:(UIImage *)image;
- (void)sendAction:(SEL)aSelector :(id)anObject :(BOOL)flag;
- (id)taggedView:(NSInteger)tag;
- (instancetype)initWithWidth:(CGFloat)width andHeight:(CGFloat)height;
- (instancetype)initWith:(int)width and:(int)height;  // Never do this.

8. 变量

首选
@interface RWTTutorial : NSObject

@property (strong, nonatomic) NSString *tutorialName;

@end
不可选
@interface RWTTutorial : NSObject {
  NSString *tutorialName;
}

9. Property属性

首选
@property (weak, nonatomic) IBOutlet UIView *containerView;
@property (strong, nonatomic) NSString *tutorialName;
不可选
@property (nonatomic, weak) IBOutlet UIView *containerView;
@property (nonatomic) NSString *tutorialName;
首选
@property (copy, nonatomic) NSString *tutorialName;
不可选
@property (strong, nonatomic) NSString *tutorialName;

10. 点 语法的调用

首选
NSInteger arrayCount = [self.array count];
view.backgroundColor = [UIColor orangeColor];
[UIApplication sharedApplication].delegate;
不可选
NSInteger arrayCount = self.array.count;
[view setBackgroundColor:[UIColor orangeColor]];
UIApplication.sharedApplication.delegate;

11.不可变实例的赋值

首选
NSArray *names = @[@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul"];
NSDictionary *productManagers = @{@"iPhone": @"Kate", @"iPad": @"Kamal", @"Mobile Web": @"Bill"};
NSNumber *shouldUseLiterals = @YES;
NSNumber *buildingStreetNumber = @10018;
不可选
NSArray *names = [NSArray arrayWithObjects:@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul", nil];
NSDictionary *productManagers = [NSDictionary dictionaryWithObjectsAndKeys: @"Kate", @"iPhone", @"Kamal", @"iPad", @"Bill", @"Mobile Web", nil];
NSNumber *shouldUseLiterals = [NSNumber numberWithBool:YES];
NSNumber *buildingStreetNumber = [NSNumber numberWithInteger:10018];

12.常量

首选
static NSString * const DeliCompanyAddress = @"www.delicloud.com";

static CGFloat const RWTImageThumbnailHeight = 50.0;
不可选
#define DeliCompanyAddress @"www.delicloud.com"

#define thumbnailHeight 2

13.枚举类型

举个例子:
typedef NS_ENUM(NSInteger, RWTLeftMenuTopItemType) {
  RWTLeftMenuTopItemMain,
  RWTLeftMenuTopItemShows,
  RWTLeftMenuTopItemSchedule
};
typedef NS_ENUM(NSInteger, RWTGlobalConstants) {
  RWTPinSizeMin = 1,
  RWTPinSizeMax = 5,
  RWTPinCountMin = 100,
  RWTPinCountMax = 500,
};
不可选
enum GlobalConstants {
  kMaxPinSize = 5,
  kMaxPinCount = 500,
};

14.各种类型的判断(Switch

switch (condition) {
  case 1:
    // ...
    break;
  case 2: {
    // ...
    // 多行需要用到括号
    break;
  }
  case 3:
    // ...
    break;
  default: 
    // ...
    break;
}
switch (condition) {
  case 1:
    // ** 注释移除`break`的原因 **
  case 2:
    // code executed for values 1 and 2
    break;
  default: 
    // ...
    break;
}
RWTLeftMenuTopItemType menuType = RWTLeftMenuTopItemMain;

switch (menuType) {
  case RWTLeftMenuTopItemMain:
    // ...
    break;
  case RWTLeftMenuTopItemShows:
    // ...
    break;
  case RWTLeftMenuTopItemSchedule:
    // ...
    break;
}

15. 私有属性

举个例子:
@interface RWTDetailViewController ()

@property (strong, nonatomic) GADBannerView *googleAdView;
@property (strong, nonatomic) ADBannerView *iAdView;
@property (strong, nonatomic) UIWebView *adXWebView;

@end

16. Booleans

首选
if (someObject) {}
if (![anotherObject boolValue]) {}
不可选
if (someObject == nil) {}
if ([anotherObject boolValue] == NO) {}
if (isAwesome == YES) {} // Never do this.
if (isAwesome == true) {} // Never do this.
@property (assign, getter=isEditable) BOOL editable;

17. 判断条件if

首选
if (!error) {
  return success;
}
不可选
if (!error)
  return success;
if (!error) return success;

18. 三元运算符

首选
NSInteger value = 5;
result = (value != 0) ? x : y;

BOOL isHorizontal = YES;
result = isHorizontal ? x : y;
不可选
result = a > b ? x = c > d ? c : d : y;

19. 初始化方法

模版
- (instancetype)init {
  self = [super init];
  if (self) {
    // ...
  }
  return self;
}

20. 类的构造函数方法

举个例子:
@interface Airplane
+ (instancetype)airplaneWithType:(RWTAirplaneType)type;
@end

21. CGRect功能


在计算矩形的结果之前,将CGRect数据结构作为输入的所有函数都隐式地标准化了这些矩形。因此,应用程序应该避免直接读写存储在CGRect数据结构重的数据。相反,使用这里描述的函数来操作矩形并检索他们的特征
首选
CGRect frame = self.view.frame;

CGFloat x = CGRectGetMinX(frame);
CGFloat y = CGRectGetMinY(frame);
CGFloat width = CGRectGetWidth(frame);
CGFloat height = CGRectGetHeight(frame);
CGRect frame = CGRectMake(0.0, 0.0, width, height);
不可选
CGRect frame = self.view.frame;

CGFloat x = frame.origin.x;
CGFloat y = frame.origin.y;
CGFloat width = frame.size.width;
CGFloat height = frame.size.height;
CGRect frame = (CGRect){ .origin = CGPointZero, .size = frame.size };

22. 黄金路线

首选
- (void)someMethod {
  if (![someOther boolValue]) {
    return;
  }

  //Do something important
}
不可选
- (void)someMethod {
  if ([someOther boolValue]) {
    //Do something important
  }
}

23. 黄金路线

首选
NSError *error;
if (![self trySomethingWithError:&error]) {
  // Handle Error
}
不可选
NSError *error;
[self trySomethingWithError:&error];
if (error) {
  // Handle Error
}

24. 单例

+ (instancetype)sharedInstance {
  static id sharedInstance = nil;

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

  return sharedInstance;
}

25. 换行符

例如
self.productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];
self.productsRequest = [[SKProductsRequest alloc] 
  initWithProductIdentifiers:productIdentifiers];

26. 换行符

首选
:]
不可选
:)

27. Xcode工程

其他Objective-C风格指南

谷歌代码规范

上一篇 下一篇

猜你喜欢

热点阅读