GCD
GCD5个不同队列
Main Queue
High Priority Queue
Default Priority Queue
Low Priority Queue
Background Priority Queue(优先级低,用于I/O)
将一个函数在主线程执行的4种方法
-
GCD方法,通过向主线程队列发送一个block块,使block里的方法可以在主线程中执行
dispatch_async(dispatch_get_main_queue(), ^{ //需要执行的方法 });
-
NSOperation 方法
//主队列 NSOperationQueue *mainQueue = [NSOperationQueue mainQueue]; NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{ //需要执行的方法 }]; [mainQueue addOperation:operation];
-
NSThread 方法
[self performSelector:@selector(method) onThread:[NSThread mainThread] withObject:nil waitUntilDone:YES modes:nil]; [self performSelectorOnMainThread:@selector(method) withObject:nil waitUntilDone:YES]; [[NSThread mainThread] performSelector:@selector(method) withObject:nil];
-
RunLoop方法
[[NSRunLoop mainRunLoop] performSelector:@selector(method) withObject:nil];
计时器
- 计时器只能调用实例方法,但是可以在这个实例方法里面调用静态方法。
- 使用计时器需要注意,计时器一定要加入RunLoop中,并且选好model才能运行。scheduledTimerWithTimeInterval方法创建一个计时器并加入到RunLoop中所以可以直接使用。
- 如果计时器的repeats选择YES说明这个计时器会重复执行,一定要在合适的时机调用计时器的invalid。不能在dealloc中调用,因为一旦设置为repeats 为yes,计时器会强持有self,导致dealloc永远不会被调用,这个类就永远无法被释放。比如可以在viewDidDisappear中调用,这样当类需要被回收的时候就可以正常进入dealloc中了。
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
-(void)timerMethod
{
//调用类方法
[[self class] staticMethod];
}
-(void)invalid
{
[timer invalid];
timer = nil;
}
重写类方法
- 在子类中实现一个同基类名字一样的静态方法
- 在调用的时候不要使用类名调用,而是使用[self class]的方式调用。原理,用类名调用是早绑定,在编译期绑定,用[self class]是晚绑定,在运行时决定调用哪个方法
@synthesize和@dynamic
- 通过@synthesize 指令告诉编译器在编译期间产生getter/setter方法
- 通过@dynamic指令,自己实现方法
懒加载
- 实际上是重写属性的getter方法
- 需要注意在getter方法里切勿使用
self.
,因为self.
会调用getter方法,造成死循环
网友评论