我有一个类方法,我在其中创建并返回类对象。 但我想在同一个类中访问该对象的某些属性。作为一个类方法,我不能在.h文件中声明变量,然后在其他方法中访问它。以下是代码 如何在下面的实例方法中访问backsprite或hudlayer对象的值?
// class 1
+(id)HUDWithBackgroundSprite:(NSString *)spriteName withRect:(CGRect)rect atPoistion:(HUDPosition)pos
{
HUDlayer *hud = [[HUDlayer alloc] init];
CCSprite *backSprite = [CCSprite spriteWithFile:spriteName];
[backSprite setContentSize:CGSizeMake(rect.size.width,rect.size.height)];
[backSprite setPosition:ccp(rect.origin.x,rect.origin.y)];
[backSprite setTag:100];
[hud addChild:backSprite];
[hud setTag:2];
return [hud autorelease];
}
// access it here
-(void)AddButtonToHUDWithImage:(NSString *)imageName selector:(SEL)selector withDisabledImage:(NSString *)disbdImageName
{
HUDlayer *hud = (HUDlayer *)[self getChildByTag:2];
CCMenuItem *menuItem1 = [CCMenuItemImage itemFromNormalImage:imageName selectedImage:imageName disabledImage:disbdImageName target:self selector:@selector(selector)];
CCMenu *menu = [CCMenu menuWithItems:menuItem1,nil];
CCSprite *sprite = (CCSprite *)[hud getChildByTag:100];
CGPoint pos = sprite.position;
//pos =[[CCDirector sharedDirector]convertToGL:pos];
[menu setPosition:ccp(pos.x+160,pos.y-30)];
[hud addChild:menu];
}
// class 2
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
HUDlayer *hud = [HUDlayer node];
// [scene addChild:hud z:1];
// 'layer' is an autorelease object.
HelloWorldLayer *layer = [[[HelloWorldLayer alloc]initWithHUD:hud]autorelease];
// add layer as a child to scene
[scene addChild: layer];
id mainHuds = [HUDlayer HUDWithBackgroundSprite:HUDBackground withRect:CGRectMake(160,450, 300,60) atPoistion:pos_Top];
SEL callOnClick;
[mainHuds AddButtonToHUDWithImage:ButtonBackground selector:callOnClick withDisabledImage:disabledBackground];
[scene addChild: mainHuds];
// return the scene
return scene;
}
我无法通过标签访问它,因为这里没有添加+方法中的HUDlayer对象,而是调用该方法的另一个类。
答案 0 :(得分:4)
您绝对可以在该类的类访问实例/成员变量的静态方法中使用指向该类实例的指针/引用。这是一个简单的例子......对不起,如果有拼写错误......
// HUDLayer.h
@interface HUDLayer : CCLayer
{
NSString* aString;
}
@property (nonatomic, retain) NSString* aString;
+(void)modifyInstanceString:(HUDLayer*)hud;
// HUDLayer.m
@implementation HUDLayer
@synthesize aString;
-(id)init
{
if ((self=[super init]))
{
self.aString = @"initial value";
}
CCLOG(@"Initial value = %@", self.aString);
return self;
}
+(void)modifyInstanceString:(HUDLayer*)hud
{
hud.aString = @"Something else";
CCLOG(@"Modified aString via static method = %@", hud.aString);
}
@end
// HelloWorldLayer.m(或任何地方)
HUDLayer* hud = [[HUDLayer alloc] init];
[HUDLayer modifyInstanceString:hud];
答案 1 :(得分:1)
没有理由不能将对象声明为.h文件中的变量:
HUDlayer * hud;
这正是该类的方法将如何访问它。如果您遇到错误,我只能假设.h文件的布局错误。我通常像这样设置场景和图层:
@interface ExampleLayer : CCLayer
{
//vars
}
//methods
@end
@interface ExampleScene : CCScene
{
ExampleLayer *layer;
}
@end
答案 2 :(得分:0)
静态方法中只能使用静态变量... 将.h文件中的对象声明为Static HUDlayer * hud; 并使用类名访问它... 仍然M不能理解你为什么要创建这么多静态方法,因为它们很重,并且即使你不需要那个类就预先加载....