Warning “…may not respond to…” を意図的に表示させない方法
by borealkiss
例えば、NSProxyのサブクラスにメッセージのフォワーディングをさせたい時 †1などにどうしてもこの警告が表示されてしまう。存在しないメソッドを呼んでいるので警告が出るのは当たり前だが放置しておくにはうっとおしい。この警告、実は簡単に消すことができる。
Solution
“…may not respond to…”が表示されるクラスのカテゴリを新規に作成し(インターフェイスのみ)、その中に”…may not respond to…”が表示されるメソッドを定義してやる。インターフェイスは”…may not respond to…”が表示されるファイルの一番上にでも書いておけばよいだろう。
Example
以下の例ではMyObjectクラスの-[MyClass doSomething]をメインスレッドで実行する際にNSProxyのフォワーディングを利用している。-[MyObject doSomethingOnMainThread]に注目してもらいたい。-[NSObject performSelectorOnMainThread:withObject:waitUntilDone:]をNSProxyのサブクラス(MyProxy)に送っているがMyProxy ()カテゴリのおかげで”…may not respond to…”の警告が表示されない。
// // MyObject.m // #import "MyProxy.h" //This is important!! @interface MyProxy () -(void)doSomething; @end @implementation MyObject -(void)doSomethingOnMainThread{ MyProxy *myProxy = [[[MyProxy alloc] initWithTarget:self] autorelease]; //No warnings!! [myProxy doSomething]; } -(void)doSomething{ //Does something. } @end
// // MyProxy.h // #import <Foundation/Foundation.h> @interface MyProxy : NSProxy { id _target; } -(id)initWithTarget:(id)aTarget; @end
// // MyProxy.m // #import "MyProxy.h" @implementation MyProxy -(id)initWithTarget:(id)aTarget{ _target = aTarget; return self; } //Override -(NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector{ return [_target methodSignatureForSelector:aSelector]; } //Override -(void)forwardInvocation:(NSInvocation *)anInvocation{ [anInvocation performSelectorOnMainThread:@selector(invokeWithTarget:) withObject:_target waitUntilDone:NO]; } -(void)dealloc{ _target = nil; [super dealloc]; } @end
Reference
Footnotes
- メッセージフォワーディングの具体例は-[NSObject performSelector:withObject]に複数の引数を渡す – boreal-kiss.com [↩]