Управление памятью в iphone cocos2d - PullRequest
2 голосов
/ 27 мая 2010

Я разрабатываю приложение для iPhone для iPhone с использованием cocos2d. Я использую более 150 изображений (наверное). Проблема в том, что при переходе с одной страницы на другую изображения зависают случайным образом ......

Я пробовал это также [[TextureMgr sharedTextureMgr] removeAllTextures];, но тщетно. Я думаю, что проблема с памятью. Ниже мой код для всех страниц:

-(id)init
{
    if( (self=[super init] )) {
        self.isTouchEnabled = YES;
        [SimpleAudioEngine sharedEngine];
        NSLog(@"b4 cover");
        Sprite *bg1 = [Sprite spriteWithFile:@"a.jpg"];
        bg1.anchorPoint = CGPointZero;
        [self addChild:bg1 z:-1];
        once = TRUE;
        soundId = [[SimpleAudioEngine sharedEngine] playEffect:@".mp3"];
    }
    return self;
}

-(void) transitionfront:(id) sender
{
    [[SimpleAudioEngine sharedEngine] stopEffect:soundId];
    soundId1 = [[SimpleAudioEngine sharedEngine] playEffect:@"page_turn.mp3"];
    flip = [[Sprite spriteWithFile:@"a.jpg"] retain];
    [self addChild: flip z:1];
    [flip setPosition:ccp(160,240)];
    Animation* animation1 = [Animation animationWithName:@"Page1" delay:0.09];
    for( int i=1;i<4;i++)
        [animation1 addFrameWithFilename: [NSString stringWithFormat:@".jpg", i]];

    id action = [Animate actionWithAnimation: animation1];
    //id action = [RepeatForever actionWithAction:[Animate actionWithAnimation: animation1]]; 
    [flip runAction:action];
    [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(moveforward) userInfo:nil repeats:NO];
}

-(void) moveforward
{
    [[SimpleAudioEngine sharedEngine] stopEffect:soundId1];
    [[Director sharedDirector] replaceScene: [ [Scene node] addChild: [nextpage node] z:0] ];
}

-(void) transitionback:(id) sender
{
    [[SimpleAudioEngine sharedEngine] stopEffect:soundId];
    soundId1 = [[SimpleAudioEngine sharedEngine] playEffect:@".mp3"];

    flip = [[Sprite spriteWithFile:@".jpg"] retain];
    [self addChild: flip z:1];
    [flip setPosition:ccp(160,240)];
    Animation* animation1 = [Animation animationWithName:@"Page1" delay:0.09];
    for( int i=3;i>0;i--)
        [animation1 addFrameWithFilename: [NSString stringWithFormat:@".jpg", i]];

    id action = [Animate actionWithAnimation: animation1];
    //id action = [RepeatForever actionWithAction:[Animate actionWithAnimation: animation1]]; 
    [flip runAction:action];
    [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(movebackward) userInfo:nil repeats:NO];
}

-(void) movebackward{
    //[[SimpleAudioEngine sharedEngine]stopEffect:@".mp3"];
    [[Director sharedDirector]replaceScene:[[Scene node]addChild:[b4page node] z:0]];
}

-(void) glossary :(id) sender {
    [[SimpleAudioEngine sharedEngine]stopEffect:soundId];
    [[Director sharedDirector]replaceScene:[[Scene node]addChild:[ node] z:0]];
}

-(BOOL)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint cocosTouchPoint = [touch locationInView: [touch view]];
    CGPoint point = [[Director sharedDirector] convertToGL:cocosTouchPoint];

    NSLog(@"pointx: %f pointy:%f", point.x, point.y);

    // Was a tab touched, if so, which one...
    if (CGRectContainsPoint(CGRectMake(220, 0, 100, 70), point))
    {
        if(once)
        {
            NSLog(@"enterred page1");

            [self transitionfront:nil];
            once = FALSE;
        }
    }
    if (CGRectContainsPoint(CGRectMake(0,0,60,60), point))
    {
        if(once)
        {
            NSLog(@"enterred cover");

            [self transitionback:nil];
            once = FALSE;
        }
    }

    if (CGRectContainsPoint(CGRectMake(100, 15, 30, 30), point))
    {
        if(once){
            [self glossary :nil];
            once = FALSE;
        }
    }
    return kEventHandled;
}

-(void)playEffect:(NSString*)sound{
    if(effectPlayer!=nil){
        [effectPlayer release];
    }
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:sound ofType:@"mp3"]];
    effectPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    [effectPlayer setDelegate:self];

    [effectPlayer play];
}

-(void)stopEffect
{
    [effectPlayer stop];
}

-(void) dealloc{
    [super dealloc];
}

Пожалуйста, помогите мне ........ дайте мне точное кодирование

это ошибка .....

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSCFDictionary setObject:forKey:]: attempt to insert nil value (key: aesop.mp3)'
2010-05-27 10:43:09.834 abc[276:20b] Stack: (
    11674715,
    2476006971,
    11758651,
    11758490,
    5126917,
    660698,
    660881,
    661061,
    131577,
    448857,
    120432,
    153433,
    630890,
    23694899,
    23603228,
    23630005,
    47120081,
    11459456,
    11455560,
    47114125,
    47114322,
    23633923,
    9928,
    9814
)

1 Ответ

0 голосов
/ 18 июня 2012

Что вы имеете в виду для "пошли напрасно"?

У меня была похожая проблема, и когда вы решите удалить AllTextures, вы потеряете все изображения, которые у вас есть в памяти, и тогда ваше приложение больше не найдет файл, связанный с CCSprites.

Thisпотому что метод CCSprite initWithFile добавляет текстуру в sharedTextureCache:

-(id) initWithFile:(NSString*)filename
{
    NSAssert(filename!=nil, @"Invalid filename for sprite");
    CCTexture2D *texture = [[CCTextureCache sharedTextureCache] addImage: filename];
    if( texture ) {
        CGRect rect = CGRectZero;
        rect.size = texture.contentSize;
        return [self initWithTexture:texture rect:rect];
    }

    [self release];
    return nil;
}

Также в этой строке вам не хватает «% i» для ссылки на int при формировании строки в формате:

[animation1 addFrameWithFilename: [NSString stringWithFormat:@"%i.jpg", i]];

Также вы используете анимацию, но вы должны использовать CCAnimation, например:

CCAnimation* anim = [CCAnimation animationWithFrames:frames delay:0.1f];

Помогает ли это?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...