REKitを使ってみた
REKit自体の紹介は開発者に譲ります。これはもっと広まると思う。
https://github.com/zuccoi/REKit (ProjectのGitHubページ)
https://github.com/zuccoi/REKit/blob/master/README_ja.md (日本語README)
http://runlooprun.wordpress.com/2013/02/12/rekit-intro/ (開発者による紹介、解説)
簡単に言うと、
1. ブロックによる特異メソッドの追加ができる
2. ブロックによるハンドラ付きでオブザーバの追加ができる
といったもの。。だと思います。あってますよね?
活用例はREADME、およびGitHubで公開されているプロジェクトに含まれているサンプルコードが非常にわかりやすいです。
「お、Blocksサポートしたのか!だったらこんなこともできたらいいな!」とみんなが妄想していた機能が実現しました!って感じでワクワクします。
ついでに、ちょっと遊んでみました。
動的にメソッドを追加できるのだから、ついでに可搬性を持たせてみると面白いのではと書いたのが以下。
// NSObject+REResponder.h - (NSInvocation*)invocationForSelector:(SEL)selector withKey:(id)inKey usingBlock:(id)block; // NSObject+REResponder.m - (NSInvocation*)invocationForSelector:(SEL)selector withKey:(id)inKey usingBlock:(id)block { // Responds to given selector [self respondsToSelector:selector withKey:inKey usingBlock:block]; // Get invocation NSInvocation *invocation; NSMethodSignature *signature; signature = [self methodSignatureForSelector:selector]; invocation = [NSInvocation invocationWithMethodSignature:signature]; // Configure invocation invocation.target = self; invocation.selector = selector; return invocation; }
使う方はこんな感じ。
NSInvocation* helloREKitInvocation; NSString* name = @"REKit"; helloREKitInvocation = ^(NSInvocation* invocation) { [invocation setArgument:(void*)&name atIndex:2]; return invocation; }([self invocationForSelector:@selector(helloREKit) withKey:nil usingBlock:^(id receiver, NSString* name) { NSLog(@"Hello, %@!!", name); }]); [helloREKitInvocation invoke]; #=>Hello, REKit!! NSInvocation* putsWeekInvocation; NSArray* weekStrs; weekStrs = @[@"Mon", @"Tue", @"Wed", @"Thu", @"Fri", @"Sat", @"Sun"]; putsWeekInvocation = [weekStrs invocationForSelector:@selector(putsWeek) withKey:nil usingBlock:^(id receiver) { for(NSString* w in receiver) { NSLog(@"%@", w); } }]; [putsWeekInvocation invoke]; #=> Mon Tue Wed Thu Fri Sat Sun
ほとんどコードを書いていないのに、その場で、存在しないはずのメソッドを発火するNSInvocationインスタンスが手に入る!
これは色々と面白いことができそうです。