标签:
本文参考引用(http://www.csdn.net/article/2015-06-01/2824818-objective-c-style-guide/1)
拥有良好的编码规范,能使我们的代码保持优雅,易读,易维护。我们现在从下面这些点开搞。
1.代码组织
#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 {}
2.空格
应该:
if (user.isHappy) {
//Do something
} else {
//Do something else
}
不应该:
if (user.isHappy)
{
//Do something
}
else {
//Do something else
}
3.注释
4.命名
应该:
UIButton *settingsButton;
不应该:
UIButton *setBut;
应该:
static NSTimeInterval const RWTTutorialViewControllerNavigationFadeAnimationDuration = 0.3;
不应该:
static NSTimeInterval const fadetime = 1.7;
应该:
@property (strong, nonatomic) NSString *descriptiveVariableName;
不应该:
NSString *descriptiveVariableName;
5.下划线
6.方法
应该:
- (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.
7.变量
应该:
@interface RWTTutorial : NSObject @property (strong, nonatomic) NSString *tutorialName; @end
不应该:
@interface RWTTutorial : NSObject {
NSString *tutorialName;
}
8.属性特性
应该:
@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;
9.点符号语法
应该:
NSInteger arrayCount = [self.array count]; view.backgroundColor = [UIColor orangeColor]; [UIApplication sharedApplication].delegate;
不应该:
NSInteger arrayCount = self.array.count; [view setBackgroundColor:[UIColor orangeColor]]; UIApplication.sharedApplication.delegate;
10.字面值
应该:
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];
11.常量
应该:
static NSString * const RWTAboutViewControllerCompanyName = @"RayWenderlich.com"; static CGFloat const RWTImageThumbnailHeight = 50.0;
不应该:
#define CompanyName @"RayWenderlich.com" #define thumbnailHeight 2
12.枚举
typedef NS_ENUM(NSInteger, RWTLeftMenuTopItemType) {
RWTLeftMenuTopItemMain,
RWTLeftMenuTopItemShows,
RWTLeftMenuTopItemSchedule
};
显式地赋值(展示旧的k-style常量定义):
typedef NS_ENUM(NSInteger, RWTGlobalConstants) {
RWTPinSizeMin = 1,
RWTPinSizeMax = 5,
RWTPinCountMin = 100,
RWTPinCountMax = 500,
};
13.case 语句
switch (condition) {
case 1:
// ...
break;
case 2: {
// ...
// Multi-line example using braces
break;
}
case 3:
// ...
break;
default:
// ...
break;
}
switch (condition) {
case 1:
// ** fall-through! **
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;
}
14.私有属性
@interface RWTDetailViewController () @property (strong, nonatomic) GADBannerView *googleAdView; @property (strong, nonatomic) ADBannerView *iAdView; @property (strong, nonatomic) UIWebView *adXWebView; @end
15.布尔值
Objective-C使用YES和NO。因为true和false应该只在CoreFoundation,C或C++代码使用。既然nil解析成NO,所以没有必要在条件语句比较。不要拿某样东西直接与YES比较,因为YES被定义为1和一个BOOL能被设置为8位。
这是为了在不同文件保持一致性和在视觉上更加简洁而考虑。
应该:
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;
文字和例子从这里引用Cocoa Naming Guidelines。
17.条件语句
应该:
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.Init 方法
- (instancetype)init {
self = [super init];
if (self) {
// ...
}
return self;
}
20.构造方法
@interface Airplane + (instancetype)airplaneWithType:(RWTAirplaneType)type; @end
关于更多instancetype信息,请查看NSHipster.com。
21.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
}
在成功的情况下,有些Apple的APIs记录垃圾值(garbage values)到错误参数(如果non-NULL),那么判断错误值会导致false负值和crash。
24.单例模式
+ (instancetype)sharedInstance {
static id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
这会防止possible and sometimes prolific crashes。
25.xcode 工程
26.其他规范
如果我们的编码规范不符合你的口味,可以查看其他的编码规范:
[Objective-C] 014_Objective-C 代码规范指南(上)
标签:
原文地址:http://www.cnblogs.com/superdo/p/4681257.html