简体   繁体   English

为什么不调用委托方法 - iOS

[英]Why delegate method is not called - iOS

I have an AudioRecorder class for recording audio, and I have the following code:我有一个用于录制音频的 AudioRecorder 类,我有以下代码:

_recorder = [[AVAudioRecorder alloc] initWithURL:audioFileURL settings:recordSettings error:&error];
        
if (_recorder && [_recorder prepareToRecord]) {
    [_recorder recordForDuration:10.0]; // Record for 10 seconds
    [_recorder setDelegate:self];
    [_recorder setMeteringEnabled:YES];
}

So, here self is the AudioRecorder class which is declare as:所以,这里的selfAudioRecorder类,声明为:

@interface AudioRecorder : NSObject <AVAudioRecorderDelegate>
    
@property AVAudioRecorder *recorder;
@property AVAudioSession *session;

@end

Then I have this callback method that should (but is not) called after the 10 seconds registration:然后我有这个回调方法应该(但不是)在 10 秒注册后调用:

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag {}

Why is this not called after the 10 sec registration?为什么在 10 秒注册后不调用它?

There are two common reason which make delegate methods not being called.有两个常见的原因导致委托方法未被调用。

The first one is not setting the delegate property or implementing a wrong method (ie, typo on the method).第一个是没有设置delegate属性或实现了错误的方法(即方法上的拼写错误)。 Which is not the case here.这里不是这种情况。

The second one, is that the object is released (from memory) too soon.第二个是对象过早地(从内存中)释放。 In other words, the delegate method will be called later (here ~10 seconds after), and delegate properties are almost always weak ly reference to avoid memory issue (cycle), when the object need to call its delegate method, the object doesn't exist anymore.换句话说,委托方法将在稍后调用(这里~10秒后),并且delegate属性几乎总是weak引用以避免内存问题(循环),当对象需要调用其委托方法时,对象不会'不存在了。 That's your issue.那是你的问题。 The small difference here, it's that's the parent of the delegate that is released too soon.这里的小区别是过早释放委托的父代。
Because _recorder is a property of AudioRecorder , so as long as the AudioRecorder instance exists, it will still be here and let the delegate method be called.因为_recorderAudioRecorder的属性,所以只要AudioRecorder实例存在,它仍然会在这里并让委托方法被调用。
But, the AudioRecorder is a local variable, so it will cease to exists after its scope (~after the next closing } ).但是, AudioRecorder是一个局部变量,因此它将在其作用域之后不复存在(~在下一次关闭之后} )。

So you need to make AudioRecorder a property of the object holding it.因此,您需要使AudioRecorder成为持有它的对象的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM