NSDictionary内存泄漏为类Var

时间:2011-09-08 18:33:18

标签: objective-c cocoa-touch memory-leaks nsdictionary

我有一个在iOS上录制音频的课程。我有一个类audioSettings的类变量,它是一个带有录音机设置的字典。我在类加载时创建此obj,然后调用recordAudio方法,我将该dict分配给录音机。录制完成后,我releasenil audioRecorder。这是代码:

- (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;

    if (!error) {
        [audioRecorder prepareToRecord];

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

这是创建字典:

 - (void) setDefaultSettings {

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

记录完成后,我设置:

[audioRecorder release];
audioRecorder = nil;

所以我可以在不释放整个课程的情况下再次使用它。

1 个答案:

答案 0 :(得分:1)

您应retain中的audioSettings setDefaultSettings或使用其他分配方法,或通过self.符号设置值。

例如,用我的方法替换你的方法:

- (void) setDefaultSettings {

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