iOS编码规范总结

1. 单个文件中保留相同的代码风格

// 不推荐

@property (nonatomic, strong) NSString *aString;

@property (strong, nonatomic) UIView *aView;

   

- (void)method1 {

   

  //666

}

   

- (void)method2

{

  //666

}

   

// 推荐

@property (nonatomic, strong) NSString *aString;

@property (nonatomic, strong) UIView *aView;

   

- (void)method1

{

  //666

}

   

- (void)method2

{

  //666

}

   

2. 搬砖不要偷懒

// 不推荐

@property (nonatomic) NSNumber *aNumber;

   

// 推荐

@property (nonatomic, strong) NSNumber *aNumber;

   

3. 合理的使用空格、换行和缩进保持代码美观

// 不推荐

-(void)myMethod{

    if(1==a){

        NSLog(@"%@",@"666");

    }

    b=1;

    a=b>1?b:2;

    c=a+b;

    d ++;

}

// 推荐

- (void)myMethod {

    

    if (1 == a) {

        NSLog(@"%@", @"666");

    }

    b = 1;

    a = (b > 1) ? b : 2;

    c = a + b;

    d++;

}

   

4. 命名和格式如果拿捏不准的话,可以参考苹果大佬的。请欣赏。

@property (nonatomic, assign) BOOL canScroll;    // 大多数人

@property (nonatomic, assign) BOOL scrollEnable; // Apple

   

5. 代码对齐,让代码美如画

// 不推荐

static NSString *const kMyStringIsLongLong = @"kMyString";

static NSString *const kYourString = @"kYourString";

static NSString *const kHeString = @"kHeString";

     

//推荐

static NSString *const kMyStringIsLongLong = @"kMyStringIsLongLong";

static NSString *const kYourString         = @"kYourString";

static NSString *const kHeString           = @"kHeString";

     

6. 方法名过长时注意换行,以 : 进行对齐。此外方法的参数最好不要超过 6 个,方法实现控制在200行以内,太长会导致可读性变差

// 不推荐

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onEnterBackground) name: UIApplicationDidEnterBackgroundNotification object:nil];

  

// 推荐

[[NSNotificationCenter defaultCenter] addObserver:self

                                         selector:@selector(onEnterBackground)

                                             name: UIApplicationDidEnterBackgroundNotification

object:nil];