开发者

NSDictionary Memory Leak as Class Var

I have a class that records audio on iOS. I have a class var of audioSettings that is a dictionary with the audio recorder settings. I create this obj once when the class loads and then the recordAudio method gets called, I assign that dict to the audio recorder. After the recording is finished I release and nil the audioRecorder. Here is the code:

- (void) recordAudio: (NSURL *) fileURL {
    NSError * error = nil;
    if (!audioSettings) {
        //If no dict, fill it
        [self setDefaultSettings];
    }   

    audioRecorder = [[AVAudioRecorder alloc] initWithURL:fileURL settings:audioSettings error:&error];

    //audioRecorder.delegate = self;

    i开发者_如何转开发f (!error) {
        [audioRecorder prepareToRecord];

        if (!audioRecorder.recording) {
            [audioRecorder record];
        }
    } else {
        NSLog(@"Create Error: %@", [error localizedDescription]);
    }
}

Here is creating the dict:

 - (void) setDefaultSettings {

     audioSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                  [NSNumber numberWithInt:AVAudioQualityMin],
                  AVEncoderAudioQualityKey,
                  [NSNumber numberWithInt:16],
                  AVEncoderBitRateKey,
                  [NSNumber numberWithInt:2],
                  AVNumberOfChannelsKey,
                  [NSNumber numberWithFloat:44100.0],
                  AVSampleRateKey, nil];
 }

After the record is finished I set:

[audioRecorder release];
audioRecorder = nil;

So I can use it again without releasing the entire class.


You should retain audioSettings in setDefaultSettings or use another allocation method or set the value via self. notation.

For example, replace your method with my one:

- (void) setDefaultSettings {

     audioSettings = [[NSDictionary dictionaryWithObjectsAndKeys:
              [NSNumber numberWithInt:AVAudioQualityMin],
              AVEncoderAudioQualityKey,
              [NSNumber numberWithInt:16],
              AVEncoderBitRateKey,
              [NSNumber numberWithInt:2],
              AVNumberOfChannelsKey,
              [NSNumber numberWithFloat:44100.0],
              AVSampleRateKey, nil] retain];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜