可以理解 @selector()就是取类方法的编号,他的行为基本可以等同C语言的中函数指针,只不过C语言中,可以把函数名直接赋给一个函数指针,而Object-C的类不能直接应用函数指针,这样只能做一个@selector语法来取.它的结果是一个SEL类型。
所以,我们可以实例化一个SEL:
SEL sel=@selector(function);
-------------
performSelector也就是主动调用SEL的方式,分为以下几种:
1:定义在NSObject中的:
- (id)performSelector:(SEL)aSelector;
对应的方法无参数。
- (id)performSelector:(SEL)aSelector withObject:(id)object;
对应一个参数的方法。
- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;
对应两个参数的方法。
如果单单只看这三个方法,似乎没有什么意义去使用这个东西来调用方法,因为完全可以直接使用self来调用对应的方法,而不需要使用SEL啊。
2:延时调用:
所以,performSelector还有其它功能,例如,延时多少秒之后再调用某个SEL;(在当前线程的Run loop中)
performSelector:(SEL) withObject:(id) afterDelay:(NSTimeInterval)
performSelector:(SEL) withObject:(id) afterDelay:(NSTimeInterval) inModes:(NSArray *)
这里的Mode参参考run loop mode;
而且它们可以被终止:
+ ( void )cancelPreviousPerformRequestsWithTarget:( id )aTarget selector:( SEL)aSelector object:( id )anArgument;
+ ( void )cancelPreviousPerformRequestsWithTarget:( id )aTarget;
3:线程相关:
performSelectorInBackground:(SEL) withObject:(id)
在后台执行某个SEL操作,一般用于异步加载网络数据,不阻塞UI.(这个方法每调用一次都会在后台新建一个线程执行对应的SEL。)这个方法对应的是:
performSelectorOnMainThread:(SEL) withObject:(id) waitUntilDone:(BOOL)
也就是在生成的线程中判断,如果当前线程结束了,也就是加载数据完成了就调用主线程的某个SEL来对UI进行刷新。
performSelector:(SEL) onThread:(NSThread *) withObject:(id) waitUntilDone:(BOOL)
指定线程执行某个SEL。