当前位置: 动力学知识库 > 问答 > 编程问答 >

selector - Objective-c performSelector: vs performSelector:withObject

问题描述:

Is calling [myObject performSelector:@selector(something) withObject:nil]; the same as just calling [myObject performSelector:@selector(something)];?

网友答案:

The only difference is signature of the method you intend on calling from the @selector. Use performSelector when the method takes no arguments, and use performSelector:withObject if the method takes a single argument of type id. Otherwise, they both do the exact same thing.

From the NSObject Protocol Reference:

Discussion

This method is the same as performSelector: except that you can supply an argument for aSelector. aSelector should identify a method that takes a single argument of type id. For methods with other argument types and return values, use NSInvocation.

As Chuck points out, this isn't really enforced (at least not at this point in time). The code below executed fine without any exceptions being thrown at me.

-(void)viewDidLoad
{
    [super viewDidLoad];    
    [self performSelector:@selector(foo) withObject:nil];
}
-(void)foo
{
    NSLog(@"foo!");
}

On the other hand, this version of the code did cause problems. So it doesn't work both ways.

-(void)viewDidLoad
{
    [super viewDidLoad];    
    [self performSelector:@selector(foo)];
}
-(void)foo:(id)myParameter
{
    NSLog(@"foo!");
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: