iOS How do access self from a class method?
I'm wondering how I can access self
from 开发者_Go百科a class method.
In this instance method I have no problem accessing self:
- (void) ccTouchesEnded:(NSSet *) touches withEvent:(UIEvent *) event{
UITouch *theTouch = [touches anyObject];
if (theTouch.tapCount == 2) {
// self is available here to change background but I need to call it from
// a class method since it's being invoked elsewhere.
[TouchTrailLayer testCall];
}
}
+ (void) testCall {
[TouchTrailLayer changeBackground];
}
How do can I refer to self in the class method below, as if it were an instance method? Or, how do you call an instance method using a class method (pick the best)?
+ (void) changeBackground {
// this is where self doesn't work
[self removeChildByTag:100 cleanup:YES];
CGSize size = [[CCDirector sharedDirector] winSize];
CCSprite *bg = [CCSprite spriteWithFile:@"Default-hd.png"];
bg.position = ccp( size.width /2 , size.height/2 );
bg.tag = 100;
[self addChild:bg z:0];
}
You can't, generally, get "self" in a static/class method because there may be no instances of the class at all, or there may be several.
However, if you know that there can only ever be one instance of the class you can implement something along the lines of a "singleton".
Singleton is very handy and can serve most of the purposes of what class methods attempt to achieve. You can, however, call self within a class method to call another class method of the same class. Another minor point is that in your instance method you can use [self class] to call your class method, instead of spelling out the class name. It's more portable and elegant imo.
精彩评论