Objective-C编程中语句和变量的一些编写规范建议

2020-01-15 13:43:39王旭

方法名与方法类型(-/+符号)间应加上一个空格。

方法段间也应该以空格间隔。

参数前应该有一个描述性的关键词。

尽可能少用”and”这个词,它不应该用来阐明有多个参数。

复制代码
// 推荐
- (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.


使用字面值来创建不可变的NSString,NSDictionary,NSArray和NSNumber对象。

 

用这种方式,注意不要将nil放在NSArray和NSDictionary里,这样会导致崩溃。

复制代码
NSArray *names = @[@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul"];
NSDictionary *productManagers = @{@"iPhone" : @"Kate", @"iPad" : @"Kamal", @"Mobile Web" : @"Bill"};
NSNumber *shouldUseLiterals = @YES;
NSNumber *buildingZIPCode = @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 *buildingZIPCode = [NSNumber numberWithInteger:10018];
避免这样的方式创建可变数组:
复制代码
NSMutableArray *aMutableArray = [@[] mutableCopy];
这样的方式,在效率和可读性上都存在问题。

 

效率:一个不必要的不可变数组被创建后马上被废弃,并没有必要。

可读性:可读性并不好。