0%

(Objective-C) 间接触发某个对象的某一方法

performSelector

  • 无参数

1
- (id)performSelector:(SEL)aSelector;
1
2
3
4
5
6
7
// eg:
- (void)aSelectorTest { NSLog(@"aSelectorTest"); }

// ex:
if ([self respondsToSelector:@selector(aSelectorTest)]) {
[self performSelector:@selector(aSelectorTest)];
}
  • 一个参数

1
- (id)performSelector:(SEL)aSelector withObject:(id)object;
1
2
3
4
5
6
7
8
9
// eg:
- (void)aSelectorTest:(NSString *)testString {
NSLog(@"aSelectorTest == %@", testString);
}

// ex:
if ([self respondsToSelector:@selector(aSelectorTest:)]) {
[self performSelector:@selector(aSelectorTest:) withObject:@"a test string"];
}
  • 两个参数

1
- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;
1
2
3
4
5
6
7
8
9
// eg:
- (void)aSelectorTest:(NSString *)testString at:(int)index {
NSLog(@"aSelectorTest == %@, index == %i", testString, index);
}

// ex:
if ([self respondsToSelector:@selector(aSelectorTest:at:)]) {
[self performSelector:@selector(aSelectorTest:at:) withObject: @"other test string" withObject: @6];
}