IOS - 执行时 (经常使用函数)
能够通过NSObject的一些方法获取运行时信息或动态运行一些消息:
/*Returns a Boolean value that indicates whether the receiving class is a subclass of, or identical to, a given class.*/
+ (BOOL)isSubclassOfClass:(Class)aClass;
/*Returns a Boolean value that indicates whether instances of the receiver are capable of responding to a given selector.*/
+ (BOOL)instancesRespondToSelector:(SEL)aSelector;
比如:if ([[Retangle class] respondsToSelector: @selector(print)]==YES)
{……}
/*Returns a Boolean value that indicates whether the receiver is an instance of a given class.*/
- (BOOL)isMemberOfClass:(Class)aClass;
比如:[obj isMemberOfClass:[Retangle class]];
除此之外还有:
conformsToProtocol 检查对象是否实现了指定协议类的方法
methodForSelector 返回指定方法实现的地址
performSelector:withObject 运行SEL 所指代的方法
- (id)performSelector:(SEL)aSelector;
- (id)performSelector:(SEL)aSelector withObject:(id)object;
- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;
这三个方法,均为同步运行。与线程无关。主主线程和子一程中均可调用成功。等同于直接调用该方法。在须要动态的去调用方法的时候去使用。
比如:[self performSelector:@selector(test2)] 与[self test2];运行效果上全然同样。
- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay inModes:(NSArray
*)modes;
- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay;
这两个方法为异步运行。即使delay传參为0,仍为异步运行。仅仅能在主线程中运行,在子线程中不会调到aSelector方法。可用于当点击UI中一个button会触发一个消耗系统性能的事件,在事件运行期间button会一直处于高亮状态,此时能够调用该方法去异步的处理该事件,就能避免上面的问题。
在方法未到运行时间之前。取消方法为:
+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget selector:(SEL)aSelector object:(id)anArgument;
+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget;
注意:调用该方法之前或在该方法所在的viewController生命周期结束的时候去调用取消函数,以确保不会引起内存泄露。
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait modes:(NSArray
*)array;
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
这两个方法,在主线程和子线程中均可运行,均会调用主线程的aSelector方法
假设wait传YES,则为异步运行,假设wait传NO,则为同步运行。
注意:apple不同意程序猿在主线程以外的线程中对ui进行操作,此时我们必须调用performSelectorOnMainThread函数在主线程中完毕UI的更新
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait modes:(NSArray
*)array;
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;
调用指定线程中的某个方法。分析效果同3。
- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg 起子线程在后台运行