Re: Objective-Cの残念な子なところ
Objective-Cの残念な子なところ - soutaroブログ
それ、(ARC使っていれば)RAIIでもっと簡潔にできると思います。
@interface AutoTimer : NSObject -(void)report; @end @implementation AutoTimer { NSString *label; NSDate *start; } -(id)initWithLabel:(NSString*)labelText { self = [super init]; if (self) { label = labelText; start = [NSDate date]; } return self; } -(void)report { NSLog(@"%@: %g[sec]", label, -[start timeIntervalSinceNow]); } -(void)dealloc { [self report]; } @end
あとは以下のようにして時間を測れます。blocksではないので__blockは必要ありませんし、いくらか試行錯誤もしやすくなるんじゃないかと思います *1。
-(void)foo { id t = [[AutoTimer alloc] initWithLabel:@"a"]; sleep(1); // 何かする } // -> a: 1.00112[sec] { id t = [[AutoTimer alloc] initWithLabel:@"b"]; sleep(2); // 何かする } // -> b: 2.00103[sec] }
*1:そのかわり "unused variable" warningが出ますが…。