iPhone SDK: у меня проблемы с памятью, может кто-нибудь помочь новичку исправить их? - PullRequest
3 голосов
/ 29 июня 2009

Я разрабатывал на платформе iPhone очень короткое время, и у меня уже была своя доля ошибок синтаксиса, а теперь проблемы с памятью.

В моем приложении для iPhone представление изображений несколько раз анимируется различными кнопками (6), и это без проблем работает на iPhone, но когда я впервые протестировал свое приложение с инструментами, он обнаружил 1 или 2 памяти Утечки, утечки памяти происходят, когда вызывается IBAction, который выполняет анимацию и это звуковой эффект. Теперь я понимаю, что такое утечка памяти, но мало знаю о том, как их предотвратить,

Стоит ли мне даже беспокоиться из-за утечки памяти в несколько килобайт, учитывая, что я планирую добавить больше анимаций позже? Помощь будет высоко оценена. Вот мой код:

#import "00001111ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
@implementation 00001111ViewController


@synthesize leftSwitch;
@synthesize rightSwitch;
@synthesize switchView;
@synthesize myScrollView1;
@synthesize img;
- (void)viewDidLoad {

    blinkTimer = [NSTimer scheduledTimerWithTimeInterval:(1.00/1.00) target:self selector:@selector(blink) userInfo:nil repeats:NO];
    [blinkTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:rand()%10]];
}

- (void)blink{
    [self animateBlink];
}

- (void)animateBlink{

    UIImage *openeye = [UIImage imageNamed:@"img.png"];
    UIImage *closedeye = [UIImage imageNamed:@"cloudnewimprovedblinked.png"];

    if(img.image == openeye)    
        img.image = closedeye;
else if(img.image == closedeye)
        img.image = openeye;

else 
    img.image ==  closedeye;
    blinkTimer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(blink) userInfo:nil repeats:NO];
if (img.image == openeye)
    [blinkTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:rand()%10]];
}
-(IBAction)toggleShowHide2:(id)sender
{

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    [switchView setAlpha:0];
    [UIView commitAnimations];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    [myScrollView1 setAlpha: 0];
    [UIView commitAnimations];
}
-(IBAction)toggleShowHide1:(id)sender
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    [myScrollView1 setAlpha: 1];
    [UIView commitAnimations];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    [switchView setAlpha:.88];
    [UIView commitAnimations];
}
- (IBAction)startClick:(id)sender{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    [switchView setAlpha:0];
    [UIView commitAnimations];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    [myScrollView1 setAlpha: 0];
    [UIView commitAnimations];
    sound1=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"clickwithsilence" ofType:@"wav"]] error:NULL];
    animationTimer = [NSTimer scheduledTimerWithTimeInterval:(1.00/30.00) target:self selector:@selector(tick) userInfo:nil repeats:NO];

    img.animationImages = [NSArray arrayWithObjects:
                              [UIImage imageNamed: @"imgapple0001.png"],
                              [UIImage imageNamed: @"imgapple0002.png"],
                              [UIImage imageNamed: @"imgapple0003.png"],
                              [UIImage imageNamed: @"imgapple0004.png"],
                              [UIImage imageNamed: @"imgapple0005.png"],
                              [UIImage imageNamed: @"imgapple0006.png"],
                              [UIImage imageNamed: @"imgapple0007.png"],
                              [UIImage imageNamed: @"imgapple0008.png"],
                              [UIImage imageNamed: @"imgapple0009.png"],
                              [UIImage imageNamed: @"imgapple0010.png"],
                              [UIImage imageNamed: @"imgapple0011.png"],
                              [UIImage imageNamed: @"imgapple0013.png"],
                              [UIImage imageNamed: @"imgapple0014.png"],
                              [UIImage imageNamed: @"imgapple0015.png"],
                              [UIImage imageNamed: @"imgapple0016.png"],
                              [UIImage imageNamed: @"imgapple0017.png"],
                              [UIImage imageNamed: @"imgapple0018.png"],
                              [UIImage imageNamed: @"imgapple0019.png"],
                              [UIImage imageNamed: @"imgapple0020.png"],nil];

    [img setAnimationRepeatCount:1];
    img.animationDuration =.7;
    [img startAnimating];
    [sound1 play];
}
- (void)tick{
    [self animateYes];
}
- (void)animateYes{

    UIImage *YesImage13=[UIImage imageNamed:@"imgapple0020.png"];


    if(img.image == YesImage13)
        img.image = YesImage13;
    else
        img.image = YesImage13;
    if(img.image == YesImage13)

        blinkTimer2 = [NSTimer scheduledTimerWithTimeInterval:(1.00/1.00) target:self selector:@selector(blink2) userInfo:nil repeats:NO];
    [blinkTimer2 setFireDate:[NSDate dateWithTimeIntervalSinceNow:rand()%7]];
}

- (void)blink2{
    [self animateBlink2];
}

- (void)animateBlink2{

    UIImage *openeye2 = [UIImage imageNamed:@"imgapple0020.png"];
    UIImage *closedeye2 = [UIImage imageNamed:@"appleblinked.png"];

    if(img.image == openeye2)   
        img.image = closedeye2;
    else if(img.image == closedeye2)
        img.image = openeye2;

    else 
        img.image ==  closedeye2;
    blinkTimer2 = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(blink2) userInfo:nil repeats:NO];
    if (img.image == openeye2)
        [blinkTimer2 setFireDate:[NSDate dateWithTimeIntervalSinceNow:rand()%10]];







}
- (IBAction)startClick1:(id)sender{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.2];
    [switchView setAlpha:0];
    [UIView commitAnimations];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    [myScrollView1 setAlpha: 0];
    [UIView commitAnimations];
    sound2=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"explosiontrimmed" ofType:@"wav"]] error:NULL];
    animationTimer1 = [NSTimer scheduledTimerWithTimeInterval:(1.00/30.00) target:self selector:@selector(tick1) userInfo:nil repeats:NO];
    img.animationImages = [NSArray arrayWithObjects:
                              [UIImage imageNamed: @"img0015.png"],
                              [UIImage imageNamed: @"img0016.png"],
                              [UIImage imageNamed: @"img0017.png"],
                              [UIImage imageNamed: @"img0018.png"],
                              [UIImage imageNamed: @"img0019.png"],
                              [UIImage imageNamed: @"img0020.png"],
                              [UIImage imageNamed: @"img0021.png"],
                              [UIImage imageNamed: @"img0022.png"],
                              [UIImage imageNamed: @"img0023.png"],
                              [UIImage imageNamed: @"img0024.png"],
                              [UIImage imageNamed: @"img0025.png"],
                              [UIImage imageNamed: @"img0026.png"],
                              [UIImage imageNamed: @"img0027.png"],
                              [UIImage imageNamed: @"img0028.png"],
                              [UIImage imageNamed: @"img0029.png"],
                              [UIImage imageNamed: @"img0030.png"],
                              [UIImage imageNamed: @"img0031.png"],
                              [UIImage imageNamed: @"img0032.png"],
                              [UIImage imageNamed: @"img0033.png"],
                              [UIImage imageNamed: @"img0034.png"],
                              [UIImage imageNamed: @"img0035.png"],
                              [UIImage imageNamed: @"img0036.png"],
                              [UIImage imageNamed: @"img0037.png"],
                              [UIImage imageNamed: @"img0038.png"],
                              [UIImage imageNamed: @"img0039.png"],
                              [UIImage imageNamed: @"img0040.png"],
                              [UIImage imageNamed: @"img0041.png"],
                              [UIImage imageNamed: @"img0042.png"],
                              [UIImage imageNamed: @"img0043.png"],
                              [UIImage imageNamed: @"img0044.png"],
                              [UIImage imageNamed: @"img0045.png"],
                              [UIImage imageNamed: @"img0046.png"],
                              [UIImage imageNamed: @"img0047.png"],
                              [UIImage imageNamed: @"img0048.png"],
                              //and so on to 100
                              nil];

    [img setAnimationRepeatCount:1];
    img.animationDuration =2.7;
    [img startAnimating];
    [sound2 play];
}
- (void)tick1{
    [self animateYes1];
}
- (void) animateYes1{

    UIImage *YesImage11=[UIImage imageNamed:@"img0048.png"];


    if(img.image == YesImage11)
        img.image = YesImage11;
    else
        img.image = YesImage11;
    if(img.image == YesImage11)

    blinkTimer1 = [NSTimer scheduledTimerWithTimeInterval:(1.00/1.00) target:self selector:@selector(blink1) userInfo:nil repeats:NO];
    [blinkTimer1 setFireDate:[NSDate dateWithTimeIntervalSinceNow:rand()%7]];
}

- (void)blink1{
    [self animateBlink1];
}

- (void)animateBlink1{

    UIImage *openeye1 = [UIImage imageNamed:@"img0048.png"];
    UIImage *closedeye1 = [UIImage imageNamed:@"explosionblinked.png"];

    if(img.image == openeye1)   
        img.image = closedeye1;
    else if(img.image == closedeye1)
        img.image = openeye1;

    else 
        img.image ==  closedeye1;
    blinkTimer1 = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(blink1) userInfo:nil repeats:NO];
    if (img.image == openeye1)
        [blinkTimer1 setFireDate:[NSDate dateWithTimeIntervalSinceNow:rand()%7]];
}








- (IBAction)startClick2:(id)sender{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.2];
    [switchView setAlpha:0];
    [UIView commitAnimations];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    [myScrollView1 setAlpha: 0];
    [UIView commitAnimations];
    sound3=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"watersplashsilence" ofType:@"wav"]] error:NULL];
    animationTimer2 = [NSTimer scheduledTimerWithTimeInterval:(1.00/30.00) target:self selector:@selector(tick2) userInfo:nil repeats:NO];

    img.animationImages = [NSArray arrayWithObjects:

                              [UIImage imageNamed: @"imgshark0001.png"],
                              [UIImage imageNamed: @"imgshark0002.png"],
                              [UIImage imageNamed: @"imgshark0003.png"],
                              [UIImage imageNamed: @"imgshark0004.png"],
                              [UIImage imageNamed: @"imgshark0005.png"],
                              [UIImage imageNamed: @"imgshark0006.png"],
                              [UIImage imageNamed: @"imgshark0007.png"],
                              [UIImage imageNamed: @"imgshark0008.png"],
                              [UIImage imageNamed: @"imgshark0009.png"],
                              [UIImage imageNamed: @"imgshark0010.png"],
                              [UIImage imageNamed: @"imgshark0011.png"],
                              [UIImage imageNamed: @"imgshark0012.png"],
                              [UIImage imageNamed: @"imgshark0013.png"],
                              [UIImage imageNamed: @"imgshark0014.png"],
                              [UIImage imageNamed: @"imgshark0015.png"],
                              [UIImage imageNamed: @"imgshark0016.png"],
                              [UIImage imageNamed: @"imgshark0017.png"],
                              [UIImage imageNamed: @"imgshark0018.png"],
                              [UIImage imageNamed: @"imgshark0019.png"],
                              [UIImage imageNamed: @"imgshark0020.png"],
                              [UIImage imageNamed: @"imgshark0021.png"],
                              [UIImage imageNamed: @"imgshark0022.png"],
                              [UIImage imageNamed: @"imgshark0023.png"],
                              [UIImage imageNamed: @"imgshark0024.png"],
                              [UIImage imageNamed: @"imgshark0025.png"],
                              [UIImage imageNamed: @"imgshark0026.png"],
                              [UIImage imageNamed: @"imgshark0027.png"],
                              [UIImage imageNamed: @"imgshark0028.png"],
                              [UIImage imageNamed: @"imgshark0029.png"],
                              [UIImage imageNamed: @"imgshark0030.png"],
                              [UIImage imageNamed: @"imgshark0031.png"],
                              [UIImage imageNamed: @"imgshark0032.png"],
                              [UIImage imageNamed: @"imgshark0033.png"],
                              [UIImage imageNamed: @"imgshark0034.png"],nil];

    [img setAnimationRepeatCount:1];
    img.animationDuration =2.8;
    [img startAnimating];
    [sound3 play];
}
- (void)tick2{
    [self animateYes2];
}
- (void)animateYes2{

    UIImage *YesImage14=[UIImage imageNamed:@"imgshark0034.png"];


    if(img.image == YesImage14)
        img.image = YesImage14;
    else
        img.image = YesImage14;






}
- (IBAction)startClick3:(id)sender{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.2];
    [switchView setAlpha:0];
    [UIView commitAnimations];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    [myScrollView1 setAlpha: 0];
    [UIView commitAnimations];
    sound4=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"dogsilence" ofType:@"wav"]] error:NULL];

    animationTimer3 = [NSTimer scheduledTimerWithTimeInterval:(1.00/30.00) target:self selector:@selector(tick3) userInfo:nil repeats:NO];

    img.animationImages = [NSArray arrayWithObjects:
                              [UIImage imageNamed: @"imgdog0001.png"],
                              [UIImage imageNamed: @"imgdog0002.png"],
                              [UIImage imageNamed: @"imgdog0003.png"],
                              [UIImage imageNamed: @"imgdog0004.png"],
                              [UIImage imageNamed: @"imgdog0005.png"],
                              [UIImage imageNamed: @"imgdog0006.png"],
                              [UIImage imageNamed: @"imgdog0007.png"],
                              [UIImage imageNamed: @"imgdog0008.png"],
                              [UIImage imageNamed: @"imgdog0009.png"],
                              [UIImage imageNamed: @"imgdog0010.png"],
                              [UIImage imageNamed: @"imgdog0011.png"],
                              [UIImage imageNamed: @"imgdog0012.png"],
                              [UIImage imageNamed: @"imgdog0013.png"],
                              [UIImage imageNamed: @"imgdog0014.png"],
                              [UIImage imageNamed: @"imgdog0015.png"],
                              [UIImage imageNamed: @"imgdog0016.png"],
                              [UIImage imageNamed: @"imgdog0017.png"],
                              [UIImage imageNamed: @"imgdog0018.png"],
                              [UIImage imageNamed: @"imgdog0019.png"],
                              [UIImage imageNamed: @"imgdog0020.png"],
                              [UIImage imageNamed: @"imgdog0021.png"],
                              [UIImage imageNamed: @"imgdog0022.png"],
                              [UIImage imageNamed: @"imgdog0023.png"],
                              [UIImage imageNamed: @"imgdog0024.png"],
                              [UIImage imageNamed: @"imgdog0025.png"],
                              [UIImage imageNamed: @"imgdog0026.png"],
                              [UIImage imageNamed: @"imgdog0026.png"],
                              [UIImage imageNamed: @"imgdog0028.png"],
                              [UIImage imageNamed: @"imgdog0029.png"],
                              [UIImage imageNamed: @"imgdog0030.png"],
                              [UIImage imageNamed: @"imgdog0031.png"],
                              [UIImage imageNamed: @"imgdog0032.png"],
                              [UIImage imageNamed: @"imgdog0033.png"],
                              [UIImage imageNamed: @"imgdog0034.png"],nil];

    [img setAnimationRepeatCount:1];
    img.animationDuration =2.7;
    [img startAnimating];
    [sound4 play];
}
- (void)tick3{
    [self animateYes3];

}
- (void)animateYes3{

    UIImage *YesImage14=[UIImage imageNamed:@"imgdog0034.png"];


    if(img.image == YesImage14)
        img.image = YesImage14;
    else
        img.image = YesImage14;






}
- (IBAction)startClick4:(id)sender{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.2];
    [switchView setAlpha:0];
    [UIView commitAnimations];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    [myScrollView1 setAlpha: 0];
    [UIView commitAnimations];
    sound5=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"arrowhitting" ofType:@"wav"]] error:NULL];
    animationTimer4 = [NSTimer scheduledTimerWithTimeInterval:(1.00/30.00) target:self selector:@selector(tick4) userInfo:nil repeats:NO];

    img.animationImages = [NSArray arrayWithObjects:

                              [UIImage imageNamed: @"imgarrow0001.png"],
                              [UIImage imageNamed: @"imgarrow0002.png"],
                              [UIImage imageNamed: @"imgarrow0003.png"],
                              [UIImage imageNamed: @"imgarrow0004.png"],
                              [UIImage imageNamed: @"imgarrow0005.png"],
                              [UIImage imageNamed: @"imgarrow0006.png"],
                              [UIImage imageNamed: @"imgarrow0007.png"],
                              [UIImage imageNamed: @"imgarrow0008.png"],
                              [UIImage imageNamed: @"imgarrow0009.png"],
                              [UIImage imageNamed: @"imgarrow0010.png"],
                              [UIImage imageNamed: @"imgarrow0011.png"],
                              [UIImage imageNamed: @"imgarrow0012.png"],
                              [UIImage imageNamed: @"imgarrow0013.png"],
                              [UIImage imageNamed: @"imgarrow0014.png"],
                              [UIImage imageNamed: @"imgarrow0015.png"],
                              [UIImage imageNamed: @"imgarrow0016.png"],
                              [UIImage imageNamed: @"imgarrow0017.png"],
                              [UIImage imageNamed: @"imgarrow0018.png"],
                              [UIImage imageNamed: @"imgarrow0019.png"],
                              [UIImage imageNamed: @"imgarrow0020.png"],
                              [UIImage imageNamed: @"imgarrow0021.png"],
                              [UIImage imageNamed: @"imgarrow0022.png"],
                              [UIImage imageNamed: @"imgarrow0023.png"],
                              [UIImage imageNamed: @"imgarrow0024.png"],nil];

    [img setAnimationRepeatCount:1];
    img.animationDuration =.7;
    [img startAnimating];
    [sound5 play];
}
- (void)tick4{
    [self animateYes4];
}
- (void)animateYes4{

    UIImage *YesImage15=[UIImage imageNamed:@"imgarrow0024.png"];


    if(img.image == YesImage15)
        img.image = YesImage15;
    else
        img.image = YesImage15;






}
- (IBAction)startClick5:(id)sender{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    [switchView setAlpha:0];
    [UIView commitAnimations];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    [myScrollView1 setAlpha: 0];
    [UIView commitAnimations];
    sound6=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"imgquote1" ofType:@"wav"]] error:NULL];
    animationTimer5 = [NSTimer scheduledTimerWithTimeInterval:(1.00/30.00) target:self selector:@selector(tick5) userInfo:nil repeats:NO];

    img.animationImages = [NSArray arrayWithObjects:
                              [UIImage imageNamed: @"qotebandb0000.png"],
                              [UIImage imageNamed: @"qotebandb0001.png"],
                              [UIImage imageNamed: @"qotebandb0002.png"],
                              [UIImage imageNamed: @"qotebandb0003.png"],
                              [UIImage imageNamed: @"qotebandb0004.png"],
                              [UIImage imageNamed: @"qotebandb0005.png"],
                              [UIImage imageNamed: @"qotebandb0006.png"],
                              [UIImage imageNamed: @"qotebandb0007.png"],
                              [UIImage imageNamed: @"qotebandb0008.png"],
                              [UIImage imageNamed: @"qotebandb0009.png"],
                              [UIImage imageNamed: @"qotebandb0010.png"],
                              [UIImage imageNamed: @"qotebandb0011.png"],
                              [UIImage imageNamed: @"qotebandb0012.png"],
                              [UIImage imageNamed: @"qotebandb0013.png"],
                              [UIImage imageNamed: @"qotebandb0014.png"],
                              [UIImage imageNamed: @"qotebandb0015.png"],
                              [UIImage imageNamed: @"qotebandb0016.png"],
                              [UIImage imageNamed: @"qotebandb0017.png"],
                              [UIImage imageNamed: @"qotebandb0018.png"],
                              [UIImage imageNamed: @"qotebandb0019.png"],
                              [UIImage imageNamed: @"qotebandb0020.png"],
                              [UIImage imageNamed: @"qotebandb0021.png"],
                              [UIImage imageNamed: @"qotebandb0022.png"],
                              [UIImage imageNamed: @"qotebandb0023.png"],
                              [UIImage imageNamed: @"qotebandb0024.png"],
                              [UIImage imageNamed: @"qotebandb0025.png"],
                              [UIImage imageNamed: @"qotebandb0026.png"],
                              [UIImage imageNamed: @"qotebandb0027.png"],
                              [UIImage imageNamed: @"qotebandb0028.png"],
                              [UIImage imageNamed: @"qotebandb0029.png"],
                              [UIImage imageNamed: @"qotebandb0030.png"],
                              [UIImage imageNamed: @"qotebandb0031.png"],
                              [UIImage imageNamed: @"qotebandb0032.png"],
                              [UIImage imageNamed: @"qotebandb0033.png"],
                              [UIImage imageNamed: @"qotebandb0034.png"],
                              [UIImage imageNamed: @"qotebandb0035.png"],
                              [UIImage imageNamed: @"qotebandb0036.png"],
                              [UIImage imageNamed: @"qotebandb0037.png"],
                              [UIImage imageNamed: @"qotebandb0038.png"],nil];

    [img setAnimationRepeatCount:1];
    img.animationDuration =3.1;
    [img startAnimating];
    [sound6 play];
}
- (void)tick5{
    [self animateYes5];
}
- (void)animateYes5{

    UIImage *YesImage17=[UIImage imageNamed:@"qotebandb0038.png"];


    if(img.image == YesImage17)
        img.image = YesImage17;
    else
        img.image = YesImage17;

}
- (IBAction)startClick6:(id)sender{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    [switchView setAlpha:0];
    [UIView commitAnimations];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    [myScrollView1 setAlpha: 0];
    [UIView commitAnimations];
    sound7=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"audiop" ofType:@"wav"]] error:NULL];
    animationTimer6 = [NSTimer scheduledTimerWithTimeInterval:(1.00/30.00) target:self selector:@selector(tick6) userInfo:nil repeats:NO];

    img.animationImages = [NSArray arrayWithObjects:
                              [UIImage imageNamed: @"hammer0001.png"],
                              [UIImage imageNamed: @"hammer0002.png"],
                              [UIImage imageNamed: @"hammer0003.png"],
                              [UIImage imageNamed: @"hammer0004.png"],
                              [UIImage imageNamed: @"hammer0005.png"],
                              [UIImage imageNamed: @"hammer0006.png"],
                              [UIImage imageNamed: @"hammer0007.png"],
                              [UIImage imageNamed: @"hammer0008.png"],
                              [UIImage imageNamed: @"hammer0009.png"],
                              [UIImage imageNamed: @"hammer0010.png"],
                              [UIImage imageNamed: @"hammer0011.png"],
                              [UIImage imageNamed: @"hammer0012.png"],
                              [UIImage imageNamed: @"hammer0013.png"],
                              [UIImage imageNamed: @"hammer0014.png"],
                              [UIImage imageNamed: @"hammer0015.png"],
                              [UIImage imageNamed: @"hammer0016.png"],
                              [UIImage imageNamed: @"hammer0017.png"],
                              [UIImage imageNamed: @"hammer0018.png"],
                              [UIImage imageNamed: @"hammer0019.png"],
                              [UIImage imageNamed: @"hammer0020.png"],
                              [UIImage imageNamed: @"hammer0021.png"],
                              [UIImage imageNamed: @"hammer0022.png"],
                              [UIImage imageNamed: @"hammer0023.png"],
                              [UIImage imageNamed: @"hammer0024.png"],
                              [UIImage imageNamed: @"hammer0025.png"],
                              [UIImage imageNamed: @"hammer0026.png"],
                              [UIImage imageNamed: @"hammer0027.png"],
                              [UIImage imageNamed: @"hammer0028.png"],
                              [UIImage imageNamed: @"hammer0029.png"],
                              [UIImage imageNamed: @"hammer0030.png"],
                              [UIImage imageNamed: @"hammer0031.png"],
                              [UIImage imageNamed: @"hammer0032.png"],
                              [UIImage imageNamed: @"hammer0033.png"],
                              [UIImage imageNamed: @"hammer0034.png"],nil];

    [img setAnimationRepeatCount:1];
    img.animationDuration =2.25;
    [img startAnimating];
    [sound7 play];
}
- (void)tick6{
    [self animateYes6];
}
- (void)animateYes6{

    UIImage *YesImage18=[UIImage imageNamed:@"img.png"];


    if(img.image == YesImage18)
        img.image = YesImage18;
    else
        img.image = YesImage18;






}




- (void)stopTimer
{
    [animationTimer invalidate];
    [animationTimer release];
    [animationTimer1 invalidate];
    [animationTimer1 release];
    [animationTimer2 invalidate];
    [animationTimer2 release];
    [animationTimer3 invalidate];
    [animationTimer3 release];
    [blinkTimer invalidate];
    [blinkTimer release];
}







-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:touch.view];
    img.center = location; 
}

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

// Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data



- (void)dealloc {
    [super dealloc];
    [img release];
    [sound1 release];
    [sound2 release];
    [sound3 release];
    [sound4 release];
    [sound5 release];
    [sound6 release];
    [sound7 release];
}
@end

Просто чтобы уточнить, таймеры используются для установки каждого отдельного анимационного изображения в последнем кадре в качестве изображения imageView.

Ответы [ 6 ]

3 голосов
/ 29 июня 2009

Я вижу потенциальную утечку памяти в вашем коде, где вы размещаете AVAudioPlayer объекты:

sound1=[[AVAudioPlayer alloc] initWithContentsOfURL:...

Из вашего кода видно, что переменные sound# являются переменными экземпляра, которые вы покорно освобождаете в своем методе -(void)dealloc. Однако утечка может произойти, если вы инициируете это конкретное действие более одного раза за время существования класса. Каждый раз, когда срабатывает действие, sound1 получает новый объект AVAudioPlayer и быстро теряет ссылку на старый.

Я бы предложил добавить следующее:

[sound1 release];
sound1 = [[AVAudioPlayer alloc] initWithContentsOfUrl: ...

И обязательно установите:

sound1 = nil;

В вашем методе -(id)init, чтобы первый вызов [sound1 release] не вызывал проблем.

обновление:

Основное правило для предотвращения утечек памяти: всякий раз, когда вы alloc, copy или retain объект, вы также должны release его.

Стоит ли беспокоиться о том, что несколько КБ просочились туда-сюда? Я бы сказал, да. Если вы заботитесь о своей работе, постарайтесь сделать ее как можно лучше. Я не говорю, что вы не должны никогда выпускать код с небольшой утечкой памяти. Я говорю, что небольшие утечки памяти следует считать ошибками. Они должны появиться в вашем списке «проблем, которые необходимо решить», и вам следует постараться как можно быстрее их устранить.

ответ на комментарий:

Ваш класс 00001111ViewController должен иметь метод с именем -(id)init:

- (id)init
{
    if ((self = [super init]) == nil) { return nil; }

    sound1 = nil;
    sound2 = nil;
    //...

    return self;
}

Код внутри метода init запускается при создании экземпляра вашего класса, так же, как код в методе dealloc вызывается при уничтожении экземпляра вашего класса. Обратите внимание, что если ваш суперкласс (класс, от которого наследуется 00001111ViewController) использует другой назначенный инициализатор, вы должны использовать вместо этого имя метода. В мире какао инициализаторы всегда начинаются с init, но они могут принимать дополнительные аргументы, такие как initWithNibName:bundle: или initWithContentsOfFile:.

еще одно обновление:

После некоторых размышлений, возможно, было бы лучше выделить объекты AVAudioPlayer только один раз, в вашем методе viewDidLoad.

- (void)viewDidLoad
{
    blinkTimer = [NSTimer ...
    [blinkTimer setFireDate: ...

    sound1 = [[AVAudioPlayer alloc] initWithContentsOfUrl: ...
    sound2 = [[AVAudioPlayer alloc] initWithContentsOfUrl: ...
    sound3 = [[AVAudioPlayer alloc] initWithContentsOfUrl: ...
}

После этого вам больше не нужно будет создавать их заново каждый раз, когда вы используете методы startClick. Все, что вам нужно сделать, это вызвать [sound1 play] в конце этих методов, и все будет хорошо.

1 голос
/ 29 июня 2009

Я тоже новичок в iPhone SDK (и вообще программирование без gc); Я нашел Clang / LLVM очень полезным ... вот руководство, которое я использовал:

http://www.oiledmachine.com/posts/2009/01/06/using-the-llvm-clang-static-analyzer-for-iphone-apps.html

1 голос
/ 29 июня 2009

В идеале у вас не было бы утечек памяти. Но вы можете посмотреть на это следующим образом: если при каждом клике теряется всего несколько килобайт, и кликов не будет много, это вряд ли проблема. Я видел, как инструменты сообщают об утечках памяти в коде, который не принадлежит мне (то есть, в фреймворковом коде), и это было всего несколько КБ, и это происходило очень редко, поэтому я решил, что все в порядке. Это нехорошая практика, но тратить часы на поиск утечки, которую вы все равно не можете исправить, тоже нецелесообразно.

Так что, если вы можете быть уверены, что утечка не выйдет из-под контроля, вы можете оставить ее там. Но если эта утечка произойдет много десятков или сотен раз, добавив до 100 утечек КБ, то вы можете быстро оказаться в беде. На iPhone ваши ресурсы ограничены, и утечки являются основной причиной сбоев приложений iPhone.

Чтобы помочь вам с вашим кодом, я считаю, что инструмент Clang Static Analyzer очень полезен. Здесь есть графический интерфейс для инструмента здесь . Он создаст отчет об утечках и других областях, требующих проверки в вашем коде.

ОДНА БОЛЬШЕ: Общее правило управления памятью в Objective-C: если вы выделяете, копируете или сохраняете объект, вы должны его освободить. В противном случае оставьте это в покое. Большинство утечек можно устранить, найдя любое место, где у вас есть код, например [[MyObject alloc] init], и убедитесь, что вы вызываете [MyObject release] через некоторое время после этого.

0 голосов
/ 03 июля 2009

так что да, все еще есть утечка памяти. На 3-й прессе

0 голосов
/ 29 июня 2009

Первый ответ указывает на статический анализатор, который, безусловно, является хорошей вещью для использования. Еще одна полезная вещь - это динамический анализатор, который отслеживает распределение / освобождение и доступ к памяти во время выполнения. Valgrind - это популярный динамический анализатор с открытым исходным кодом, широко распространенный в Linux.

Valgrind может работать на OSX (хотя он говорит, что он "не поддерживается, неполон и содержит ошибки"), и с небольшим взломом кто-то заставил его работать с исполняемыми файлами iPhone SDK .

Еще лучше, вы можете попробовать инструменты, которые являются частью XCode. Здесь есть учебник по запуску здесь .

0 голосов
/ 29 июня 2009

Для начала вы можете создать NSArrays с изображениями в методе init

И тогда вы можете подумать о том, чтобы найти шаблон для размещения изображений. Создайте функцию, которая зацикливается и принимает путь в качестве аргумента, который помещает изображения в массив.

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