iOS开发之Runtime函数

1. 可以通过NSObject的一些方法获取运行时信息或动态执行一些消息:
1. /*Returns a Boolean value that indicates whether the receiving class is a subclass of, or identical to, a given class.*/
1. + (BOOL)isSubclassOfClass:(Class)aClass;
1. /*Returns a Boolean value that indicates whether instances of the receiver are capable of responding to a given selector.*/
1. + (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中一个 按钮会触发一个消耗系统性能的事件,在事件执行期间按钮会一直处于高亮状态,此时可以调用该方法去异步的处理该事件,就能避免上面的问题。 在方法未到执行时间之前,取消方法为:
+ (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 起子线程在后台运行

 

你可能感兴趣的:(Runtime)