在选择器内编写方法?

时间:2013-03-29 11:33:13

标签: ios objective-c xcode methods performselector

这可能很疯狂,但我想知道我们是否可以在选择器中编写实际方法。原因是,我的方法只有一个简单的1-liner。

-(void)doThat {
    loadedPhoto.alpha = 1.0;
}

-(IBAction)revealPickers:(id)sender {

    loadedPhoto.alpha = 0.7;
    [self performSelector:@selector(doThat) withObject:nil afterDelay:1.0];
}

所以我想知道的是这样的捷径(显然这不起作用):

[self performSelector:@selector(^(void){loadedPhoto.alpha=1.0;}) withObject:nil afterDelay:1.0];

可能还是只是愚蠢?

2 个答案:

答案 0 :(得分:1)

扩展并更正我的评论:

我的评论错了,我误读了你的代码并认为你在做[self performSelectorOnMainThread:etc:]

我的实际解决方案(快速谷歌搜索后 - 并不难找到):

// Delay execution of my block for 10 seconds.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC), dispatch_get_current_queue(), ^(void){
    loadedPhoto.alpha = 1.0;
});

希望它有所帮助!

答案 1 :(得分:0)

最简单的解决方案是使用dispatch_after,但您也可以使用块适配器在NSObject上定义方法。

@interface BlockAdapter

@property (nonatomic, copy, readwrite) void (^block)();

- (void)call;

@end

@implementation BlockAdapter

- (void)call {
    self.block();
}

@end
@interface NSObject (PerformBlocks)

- (void)performBlock:((void)^())block afterDelay:(NSTimeInterval)delay;

@end

@implementation NSObject (PerformBlocks)

- (void)performBlock:((void)^())block afterDelay:(NSTimeInterval)delay {
   BlockAdapter* adapter = [[BlockAdapter alloc] init];
   adapter.block = block;

   [adapter performSelector:@selector(call) withObject:nil afterDelay:delay];
}

@end