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

2022-11-27  本文已影响0人  布呐呐u

performSelector

- (id)performSelector:(SEL)aSelector;
// eg:
- (void)aSelectorTest { NSLog(@"aSelectorTest"); }

// ex:
if ([self respondsToSelector:@selector(aSelectorTest)]) {
   [self performSelector:@selector(aSelectorTest)];
}

- (id)performSelector:(SEL)aSelector withObject:(id)object;
// eg:
- (void)aSelectorTest:(NSString *)testString {
    NSLog(@"aSelectorTest == %@", testString);
}

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

- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;
// 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];
}
上一篇 下一篇

猜你喜欢

热点阅读