Effective Objective-C读后笔记(4)
31、dispatch_once
实现单例
+ (instancetype)sharedInstance {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[self alloc] init];
});
return _instance;
}
32、多用枚举器,少用for循环
- 遍历collection的四种方式:
for
循环、NSEnumerator
、for..in..
、block遍历
。
-
block
遍历本身使用的GCD形式,效率更高。
33、NSCache的使用
- 构建缓存的时候多用
NSCache
,少用NSDictionary
。NSCache
能在收到系统内存警告的时候主动释放。
-
NSCache
是线程安全的。
-
NSCache
能够设置内存的开销。
34、+load
和+initialize
方法
-
+load
方法不参与覆写机制,类的load
方法先于分类的load
方法执行。
-
initialize
方法存在覆写机制,所以调用的时候要判断是那个类。
- 尽量精简这两个方法,提高程序的响应速度。
35、NSTimer
会保留对象
@interface NSTimer (Block)
+ (NSTimer *)sn_scheduledTimerWithTimeInterval:(NSTimeInterval)ti block:(void(^)())block repeats:(BOOL)yesOrNo;
@end
@implementation NSTimer (Block)
+ (NSTimer *)sn_scheduledTimerWithTimeInterval: (NSTimeInterval)ti block:(void (^)())block repeats:(BOOL)yesOrNo{
return [self scheduledTimerWithTimeInterval:ti target:self selector:@selector(block_Invoke:) userInfo:[block copy] repeats:yesOrNo];
}
+ (void)block_Invoke:(NSTimer *)timer{
void(^block)() = timer.userInfo;
if (block) {
block();
}
}
@end
本文标题:Effective Objective-C读后笔记(4)
本文链接:https://www.haomeiwen.com/subject/yekhcxtx.html
网友评论