iOS - 开发技巧iOS进阶

iOS - performSelector

2018-01-23  本文已影响18人  SkyMing一C
图片源于网络

1. performSelector

2. performSelector的使用

- (id)performSelector:(SEL)aSelector;

- (id)performSelector:(SEL)aSelector withObject:(id)object;

- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;

- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay inModes:(NSArray * )modes;

- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay;

+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget selector:(SEL)aSelector object:(id)anArgument;
+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget;

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait modes:(NSArray * )array;

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;

- (void)performSelector:(SEL)aSelector onThread:(NSThread * )thr withObject:(id)arg waitUntilDone:(BOOL)wait modes:(NSArray * )array;

- (void)performSelector:(SEL)aSelector onThread:(NSThread * )thr withObject:(id)arg waitUntilDone:(BOOL)wait;

- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg;

3. 示例

@interface  ClassForSelectors : NSObject

@end

@implementation ClassForSelectors
//建立一个简单的函数
- (void) fooNoInputs {
  NSLog(@"Does nothing");
}
//建立一个有1个参数的函数
- (void) fooOneIput:(NSString*) first {
  NSLog(@"Logs %@", first);
}
//建立一个有2个参数的函数
- (void) fooFirstInput:(NSString*) first secondInput:(NSString*) second {
  NSLog(@"Logs %@ then %@", first, second);
}
//调用
- (void) performMethodsViaSelectors {
  [self performSelector:@selector(fooNoInputs)];
  [self performSelector:@selector(fooOneInput:) withObject:@"first"];
  [self performSelector:@selector(fooFirstInput:secondInput:) withObject:@"first" withObject:@"second"];
}





//动态调用函数
- (NSArray *)abcWithAAA: (NSNumber *)number {
  int primaryKey = [number intValue];
  NSLog("%i", primaryKey);
}

- (void) performDynamicMethodsViaSelectors {
  MethodForSelectors * mfs = [MethodForSelectors alloc];
  NSArray *Arrays = [NSArray arrayWithObjects:@"AAA", @"BBB", nil];
  for ( NSString *array in Arrays ){
    SEL customSelector = NSSelectorFromString([NSStringstringWithFormat:@"abcWith%@:", array]);
    mfs = [[MethodForSelectors alloc] performSelector:customSelector withObject:0];
  }
}
@end



@interface  MethodForSelectors : NSObject

@end


@implementation MethodForSelectors
- (void)abcWithAAA: (NSNumber *)number {
  NSLog("%i", number);
}
@end

参考

iOS-面试官如果问你performSelector用过没?

performSelector的原理以及用法

上一篇下一篇

猜你喜欢

热点阅读