Created
May 23, 2012 09:20
-
-
Save xxd/2774188 to your computer and use it in GitHub Desktop.
performSelector -> _cmd -> objc_msgSend -> id (*IMP) (id, SEL, …)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //普通的 | |
| - (NSInteger)fibonacci:(NSInteger)n { | |
| if (n > 2) { | |
| return [self fibonacci:n - 1] + [self fibonacci:n - 2]; | |
| } | |
| return n > 0 ? 1 : 0; | |
| } | |
| //改成用_cmd实现就变成了这样: | |
| - (NSInteger)fibonacci:(NSInteger)n { | |
| if (n > 2) { | |
| return (NSInteger)[self performSelector:_cmd withObject:(id)(n - 1)] + (NSInteger)[self performSelector:_cmd withObject:(id)(n - 2)]; | |
| } | |
| return n > 0 ? 1 : 0; | |
| } | |
| //或者直接用objc_msgSend: | |
| - (NSInteger)fibonacci:(NSInteger)n { | |
| if (n > 2) { | |
| return (NSInteger)objc_msgSend(self, _cmd, n - 1) + (NSInteger)objc_msgSend(self, _cmd, n - 2); | |
| } | |
| return n > 0 ? 1 : 0; | |
| } | |
| //但是每次都通过objc_msgSend来调用显得很费劲,有没有办法直接进行方法调用呢?答案是有的,这就需要用到IMP了。IMP的定义为“id (*IMP) (id, SEL, …)”,也就是一个指向方法的函数指针。 | |
| //NSObject提供methodForSelector:方法来获取IMP,因此只需稍作修改就行了: | |
| - (NSInteger)fibonacci:(NSInteger)n { | |
| static IMP func; | |
| if (!func) { | |
| func = [self methodForSelector:_cmd]; | |
| } | |
| if (n > 2) { | |
| return (NSInteger)func(self, _cmd, n - 1) + (NSInteger)func(self, _cmd, n - 2); | |
| } | |
| return n > 0 ? 1 : 0; | |
| } | |
| //延迟 | |
| [self performSelector:@selector(performDismiss) withObject:nil afterDelay:3.0f]; | |
| //在其他Class调用 | |
| //首先new一下class,然后就可以用class里边的Function了 | |
| Fraction *frac = [[Fraction alloc] init]; | |
| [frac setNumerator: 1]; | |
| [frac setDenominator: 3]; | |
| //或者 | |
| [[Fraction alloc] performSelector:@selector(performDismiss) withObject:nil afterDelay:3.0f]; | |
| --EOF-- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment