[[AClass alloc] initWithTarget:self selector:@selector(hello:)];などとしておいて、後で AClass から [self hello:…]をコールしてもらうということがありますが、これってどうやって実現しているんでしょうか?
方法はいくつかありますが、そのうちの一つが NSInvocation を使うという方法です。
cocos2d の内部でも使われていました。
NSInvocation オブジェクトの作成は以下のようになります。
[[AClass alloc] initWithTarget:self selector:@selector(hello:)];などとしておいて、後で AClass から [self hello:…]をコールしてもらうということがありますが、これってどうやって実現しているんでしょうか?


![]() |
| 4つのサイズのテクスチャを用意 |
// Background.h
#import <foundation/foundation.h>
#import "cocos2d.h"
@interface Background : CCSprite {
}
+ (id)backgroundWithRect:(CGRect)rect;
- (id)initWithRect:(CGRect)rect;
@end
// Background.m
#import "Background.h"
@implementation Background
+ (id)backgroundWithRect:(CGRect)rect
{
return [[[self alloc] initWithRect:rect] autorelease];
}
- (id)initWithRect:(CGRect)rect
{
if ((self = [super initWithFile:@"worm64x64.png" rect:rect])) {
ccTexParams params = {GL_LINEAR,GL_LINEAR,GL_REPEAT,GL_REPEAT};
[texture_ setTexParameters:¶ms];
self.anchorPoint = CGPointZero;
}
return self;
}
backgroundWithRect: メソッドでスプライトのインスタンス化を行います。その際にrect パラメータで、スプライトのサイズとポジションを指定します。
// HelloWorldLayer.m
#import "Background.h"
-(id) init
{
if( (self=[super init])) {
CGSize size = [[CCDirector sharedDirector] winSize];
Background *bg = [Background backgroundWithRect:CGRectMake(0,0,size.width,size.height)];
[self addChild:bg];
}
return self;
}
結果は以下のようになりました。テクスチャーのサイズは64×64です。- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[[picker parentViewController] dismissModalViewControllerAnimated:YES];
[picker release];
}
しかし iOS 5 では、これだとうまく動きません。