<p class="p1"><span class="s1">@interface</span><span class="s2"> AAA : </span><span class="s3">NSObject</span></p>
- (void)aaPublic;
@end
#import "AAA.h"
@implementation AAA
- (void)aaPublic
{
NSLog(@"%s", __func__);
}
- (void)aaPrivate
{
NSLog(@"%s", __func__);
}
@end
AAA *a = [[AAA alloc] init];
[a aaPublic];
[a aaPrivate];
[a performSelector:@selector(aaPrivate) withObject:nil];
<p class="p1"><span class="s1">@interface</span><span class="s2"> AAA : </span><span class="s3">NSObject</span></p>
- (void)aaPublic;
@end
#import "AAA.h"
@implementation AAA
- (void)aaPublic
{
NSLog(@"%s", __func__);
}
- (void)aaPrivate
{
NSLog(@"%s", __func__);
}
@end
AAA *a = [[AAA alloc] init];
[a aaPublic];
[a aaPrivate];
[a performSelector:@selector(aaPrivate) withObject:nil];
PerformSelector 和 直接调用的区别
- performSelector是运行时系统负责去找方法的,在编译时候不做任何校验。而直接调用在编译期就会直接检查 如果在.h没有公开该方法就会直接报错
- performSelector可以调用.m内的私有方法 调用时要记得respondsToSelector来检查一下selector是否存在
PerformSelector的内存问题
SEL sel;
BOOL a = YES;
if (a) {
sel = @selector(test:);
}
else {
sel = @selector(test1:);
}
[self performSelector:sel withObject:nil];<p class="p1"><span class="s1"> PerformSelector may cause a leak because its selector is unknown</span></p>
SEL sel;
BOOL a = YES;
if (a) {
sel = @selector(test:);
}
else {
sel = @selector(test1:);
}
[self performSelector:sel withObject:nil];<p class="p1"><span class="s1"> PerformSelector may cause a leak because its selector is unknown</span></p>
为什么这里会有警告呢
PerformSelector一系列方法的区别
1.[selfperformSelector:@selector(test:)withObject:@"0"];
这个方法和当前线程有关,在当前线程执行这个selector
2. /**
* 这个方法是在主线程执行Selector
*
* @param选择子
*
* @return waitUntilDone Yes等待返回才继续执行 No不用等待结束继续执行
*/
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
NSLog(@"start-1");
[self performSelectorOnMainThread:@selector(test1:) withObject:@"1111" waitUntilDone:YES];
NSLog(@"finish-1");
NSLog(@"start-2");
[self performSelectorOnMainThread:@selector(test1:) withObject:@"222" waitUntilDone:NO];
NSLog(@"finish-2");
- (void)test1:(NSString *)xxx
{
sleep(5);
NSLog(@"xxx");
}
3.指定线程执行
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait modes:(NSArray *)arrayNS_AVAILABLE(10_5,2_0);
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait NS_AVAILABLE(10_5,2_0);
// equivalent to the first method with kCFRunLoopCommonModes
- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg
cancelPreviousPerformRequests
+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget selector:(SEL)aSelector object:(id)anArgument;
+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget;
如果你要指定某个selector被取消,用第一个方法。注意参数都要一样不然取消无效