Effective Objective-C 2.0笔记

1、在类的头文件中尽量少引入其他头文件

能用@class就用,可以降低类之间的耦合

2、多用字面量语法,少用与之等价的方法,特别是字典、数组

NSNumber *num = [[NSNumber alloc] initWithInt:1];    -->不好

NSNumber *num1 = @1;   -->OK

3、多用类型常量,少用#define预处理指令

#define ANIMATION_DURATION 0.3 -->不好

static const NSTimeInterval kAnimationDuration = 0.3;  -->OK

.h中

extern NSString *const XUJStringConstant;

.m中

NSString *const XUJStringConstant = @"VALUE";

4、用枚举表示状态、选项、状态码

//NS_ENUM,定义状态等普通枚举

typedef NS_ENUM(NSUInteger, XUJState) {

XUJStateOK = 0,

XUJStateError,

XUJStateUnknow

};

//NS_OPTIONS,定义选项

typedef NS_OPTIONS(NSUInteger, XUJDirection) {

XUJDirectionNone = 0,

XUJDirectionTop = 1 << 0,

XUJDirectionLeft = 1 << 1,

XUJDirectionRight = 1 << 2,

XUJDirectionBottom = 1 << 3

};

凡是需要以按位或操作来组合的枚举都应使用NS_OPTIONS,不需要互相组合用NS_ENUM。

5、读取实例变量时采用直接访问形式,设置实例变量时通过属性设置

self.name = @"smile";

NSLog(@"%@", _name);

6、用前缀避免命名空间冲突(应该是3个字母)

XUJViewController

7、提供全能初始化方法 : NS_DESIGNATED_INITIALIZER

8、实现description方法

- (NSString *)description {

return [NSString stringWithFormat:@"<%@:%p, %@>",

[self class],

self,

@{@"name:": _name,

@"firstName:": _firstName}

];

}

9、.h中属性外面只需要调用情况,将它设置成readonly,在.m中类目中改成readwrite.

10、为私有方法加前缀

11、oc中很少用try-catch(会造成内存泄漏),要用NSError

12、委托属性用weak(也不提倡用unsafe_unretained)

13、将类的视线代码分散到便于管理的数个分类中

14、为第三方类的分类名称加前缀

15、在dealloc中释放引用(CF)并解除监听

16、用@autoreleasepool降低内存峰值

NSArray *array = @[@1, @2, @3, @4];

NSMutableArray *people = [NSMutableArray new];

for (NSNumber *num in array) {

@autoreleasepool {

if (num.integerValue >= 2) {

[people addObject:num];

}}

17、多用块枚举,少用for循环

NSArray *array = @[@1, @2, @3, @4];

[array enumerateObjectsUsingBlock:^(NSNumber *num, NSUInteger idx, BOOL * _Nonnull stop) {

NSLog(@"%@", num);

}];

你可能感兴趣的:(Effective Objective-C 2.0笔记)