Как я могу инициализировать объект класса с параметрами? - PullRequest
0 голосов
/ 27 марта 2012

Я хотел бы знать: как я могу инициализировать объект класса с параметрами?

У меня есть класс для инициализации спрайта, и я хотел бы сделать его более удобным для использования.Сделайте класс для инициализации всех спрайтов, передав параметр.

Somethong, как

RolyPoly* new = [RolyPoly initWithSpriteName: [NSString stringWithFormat:@"rolypoly"]];

и в классе PolyPoly user этот параметр в

NSDictionary *rolyPolyDict = [levelDict valueForKeyPath:@"rolypoly"];

Мой класс

@interface RolyPoly : CCLayer {

    CCAction *_walkAction; 
    CCSprite *_rolypoly;
    double offsetx;
    double offsety;
}

@property (nonatomic, retain) CCSprite *rolypoly;
@property (nonatomic, retain) CCAction *walkAction;
@property (nonatomic, assign) double offsetx;
@property (nonatomic, assign) double offsety;

+(id) scene;
-(void) setOffx;
@end

//**************************************************************


@implementation RolyPoly

@synthesize rolypoly = _rolypoly;
@synthesize walkAction = _walkAction;
@synthesize  offsetx = _offsetx;
@synthesize  offsety = _offsety;

+(id) scene
{
    CCScene *scene = [CCScene node];

    return scene;
}

-(id) init
{
    if ((self = [super init]))
    {
        int currentLevel = [[SettingsManager sharedSettingsManager] getCurrentLevel];

        CGSize screenSize = [[CCDirector sharedDirector] winSize];

        NSData *xmlData = [NSData dataWithContentsOfFile:[[NSBundle bundleForClass:[self class]] pathForResource:@"gameScene" ofType:@"xml"]];

        NSError *error = nil;

        NSDictionary *dictionary = [XMLReader dictionaryForXMLData:xmlData error:&error];
        NSDictionary *levelsDict = [dictionary valueForKeyPath:@"levels.level"];
        NSDictionary *levelDict;

        for (levelDict in levelsDict)
        {

            int idLevel = [[levelDict valueForKeyPath:@"id"] intValue];
            if(idLevel==currentLevel)
            {
                NSDictionary *rolyPolyDict = [levelDict valueForKeyPath:@"rolypoly"];

                int count=[[rolyPolyDict valueForKeyPath:@"count"] intValue];

                [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile: [NSString stringWithFormat:@"rolypoly_%d.plist", currentLevel]];
                CCSpriteBatchNode *rolypolySpriteSheet = [CCSpriteBatchNode batchNodeWithFile:[NSString stringWithFormat:@"rolypoly_%d.png", currentLevel]];
                [self addChild:rolypolySpriteSheet];
                NSMutableArray *rolypolyAnimFrames = [NSMutableArray array];
                for(int i = 1; i <= count; ++i) {

                    [rolypolyAnimFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName: [NSString stringWithFormat:@"rolypoly_%d_%d.png", currentLevel, i]]];
                }
                CCAnimation *rolypolyAnim = [CCAnimation animationWithFrames:rolypolyAnimFrames delay:0.1f];
                self.rolypoly = [CCSprite spriteWithSpriteFrameName: [NSString stringWithFormat:@"rolypoly_%d_1.png", currentLevel]]; 

                self.walkAction = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:rolypolyAnim restoreOriginalFrame:NO]];
                [self.rolypoly runAction:self.walkAction];
                [rolypolySpriteSheet addChild:self.rolypoly z:1];

                self.offsetx=[[rolyPolyDict valueForKeyPath:@"offsetx"] doubleValue];
                self.offsety=[[rolyPolyDict valueForKeyPath:@"offsety"] doubleValue];
                self.position = ccp(screenSize.width*self.offsetx, screenSize.height*self.offsety);

            }    
        }

        [self scheduleUpdate];
    }
    return self;
}
-(void) setOffx
{
   // self.offsetx=x;
    NSLog(@"dsfafdaf");
}

-(void) update:(ccTime)delta
{

}
- (void) dealloc
{
    self.rolypoly = nil;
    self.walkAction = nil;
    [super dealloc];
}
    @end

1 Ответ

0 голосов
/ 27 марта 2012

Надеюсь, я правильно понимаю, чего вы пытаетесь достичь:

Просто определите новый метод в вашем классе:

-(id) initWithSpriteName:(NSString *)spriteName
{
    if self = [self init];
    {
        NSDictionary *rolyPolyDict = [levelDict valueForKeyPath:@"rolypoly"];
    }
}

Затем просто вызовите его так, как вы это обычно делаете:

RolyPoly *myRolyPoly = [[RolyPoly alloc] initWithSpriteName: [NSString stringWithFormat:@"rolypoly"]];
...