一、performselector的含义

performselector是Objective-C中一种常用的方法调用方式。它允许我们在运行时动态调用一个方法,常常用于在主线程执行一些UI操作等。
二、performselector的语法格式
- (nullable id)performSelector:(SEL)aSelector;
- (nullable id)performSelector:(SEL)aSelector withObject:(nullable id)anObject;
- (void)performSelector:(SEL)aSelector withObject:(nullable id)anObject afterDelay:(NSTimeInterval)delay;
+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget;
performselector方法有三个主要参数:方法名,调用该方法的对象,以及传递给该方法的参数。performselector调用的方法必须为public或protected。如果方法为private,则必须在调用之前使用performselector:withobject:方法注册为可调用的方法。
三、performselector的使用场景及注意事项
四、代码示例
1. 在主线程执行UI操作
- (void)updateUI:(NSData *)data {
    // 执行UI操作
}
- (void)someMethod {
    [self performSelector:@selector(updateUI:) withObject:data afterDelay:0.1];
}
2. 多个线程之间通信
- (void)updateUI:(NSData *)data {
    // 执行UI操作
}
- (void)someMethod {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 执行一些操作
        [self performSelectorOnMainThread:@selector(updateUI:) withObject:data waitUntilDone:YES];
    });
}
3. performselector引起的内存泄漏问题
- (void)someMethod {
    [self performSelector:@selector(updateUI:) withObject:data afterDelay:0.1];
    
    // 准备释放对象
    [self release];
}
- (void)dealloc {
    // 取消之前的所有延迟方法
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    
    [super dealloc];
}            
            
            
      
      
                  
                  
                  
                  
                  
                    
                    
                    
                    
                    
                    
                    
                    
      
        
京公网安备 11010802030320号