Swift:在super.init初始化自我编译错误之前的方法调用中使用'self'

游牧民族

我制作了一个自定义类来处理音频记录/播放,并Protocol在该类中放了一个Protocol在一个UIViewController类中实现,setDelegate为AudioHelper类调用了我的方法。

我遇到了与我的有关的编译错误init()不确定如何消除错误:

use of 'self' in method call 'setupAudioSession' before super.init initializes self

override init() {
        setupAudioSession()
        super.init()
    }

如何解决此错误?为什么我必须重写init()?

我的AudioHelper类

import Foundation
import AVFoundation

class AudioHelper: NSObject, AVAudioRecorderDelegate {

    var audioSession: AVAudioSession?
    var audioRecorder: AVAudioRecorder?
    var delegate: AudioRecorderProtocol?

    class var sharedInstance: AudioHelper {

        struct Static {
            static var instance: AudioHelper?
            static var token: dispatch_once_t = 0
        }

        dispatch_once(&Static.token) {
            Static.instance = AudioHelper()
        }

        return Static.instance!
    }

    override init() {
        setupAudioSession()
        super.init()
    }

    func setDelegate(delegate: AudioRecorderProtocol) {
        self.delegate = delegate
    }

    func setupAudioSession() {
        audioSession = AVAudioSession.sharedInstance()
        audioSession?.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)
        audioSession?.setActive(true, error: nil)
    }

    func createAudioMessageDirectory() {
        let fm = NSFileManager.defaultManager()
        if !fm.fileExistsAtPath(GlobalVars.kAudioMessageDirectory) {
            var error: NSError?
            if !fm.createDirectoryAtPath(GlobalVars.kAudioMessageDirectory, withIntermediateDirectories: true, attributes: nil, error: &error) {
                println("Unable to create audio message directory: \(error)")
            }
        }
    }

    // MARK: Recording

    func beginRecordingAudio() {
        createAudioMessageDirectory()
        var filepath =  GlobalVars.kAudioMessageDirectory.stringByAppendingPathComponent("audiofile.aac")
        var url = NSURL(fileURLWithPath: filepath)

        var recordSettings = [
            AVFormatIDKey: kAudioFormatMPEG4AAC,
            AVSampleRateKey: 8000.0,
            AVNumberOfChannelsKey: 1,
            AVEncoderBitRateKey: 12800,
            AVLinearPCMBitDepthKey: 16,
            AVEncoderAudioQualityKey: AVAudioQuality.Max.rawValue
        ]

        println("Recorded Audio Message Saved: \(url!)")

        var error: NSError?
        audioRecorder = AVAudioRecorder(URL: url, settings: recordSettings as [NSObject : AnyObject], error: &error)

        if error == nil {
            if audioRecorder != nil {
                audioRecorder!.delegate = self
                audioRecorder!.record()
            }
        }
        else {
            println(error!.localizedDescription)
        }
    }

    func stopRecordingAudio() {
        if audioRecorder != nil {
            audioRecorder!.stop()
        }
    }

    func handleRecordAudioButtonLongPressGestureForState(state: UIGestureRecognizerState) {
        if state == UIGestureRecognizerState.Ended {
            stopRecordingAudio()
            delegate?.onRecordAudioStop()
        }
        else if state == UIGestureRecognizerState.Began {
            beginRecordingAudio()
            delegate?.onRecordAudioStop()
        }
    }

    func audioRecorderDidFinishRecording(recorder: AVAudioRecorder!, successfully flag: Bool) {
        println("Record Audio Success: \(flag)")
        delegate?.onRecordAudioFinished()
    }

    func audioRecorderEncodeErrorDidOccur(recorder: AVAudioRecorder!, error: NSError!) {
        println("Record Audio Encode Error: \(error.localizedDescription)")
    }

    // MARK: Playback

    func playAudioMessageFromUrl(messageId: String) {
        if let url = NSURL(string: GlobalVars.kUrlAudioMessage + messageId) {
            if let data = NSData(contentsOfURL: url) {
                var error: NSError? = nil
                let audioPlayer = AVAudioPlayer(data: data, error: &error)

                if error == nil {
                    if audioPlayer != nil {
                        audioPlayer.numberOfLoops = 0
                        audioPlayer.volume = 1.0
                        audioPlayer.prepareToPlay()
                        audioPlayer.play()
                    }
                }
                else {
                    println("Audio playback error: \(error?.localizedDescription)")
                }
            }
        }
    }

}

protocol AudioRecorderProtocol {
    func onRecordAudioStart()
    func onRecordAudioStop()
    func onRecordAudioFinished()
}

我的UIViewController实现了协议(删去了多余的代码)

class ChatViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, AudioRecorderProtocol {

    let audioHelper = AudioHelper.sharedInstance

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    override func viewDidLoad() {
        super.viewDidLoad()

//        addDemoMessages()

        setupGestureRecognizer()
        setupKeyboardObserver()
        setupViews()
        setupTableView()
        audioHelper.setDelegate(self)
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        getUsersFromDb()
        getMessagesFromDb()
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        setCurrentVC()
        tableView.reloadData()

        if partnerUserId != nil && !db.doesUserExist(partnerUserId!) {
            HttpPostHelper.profileGet(userId: partnerUserId!)
        }

        requestMessagesFromServer()
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        ViewHelper.scrollTableViewToBottom(tableView)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func handleRecordAudioButtonHold(sender: UILongPressGestureRecognizer) {
        audioHelper.handleRecordAudioButtonLongPressGestureForState(sender.state)
    }

    func onRecordAudioStart() {
        dispatch_async(dispatch_get_main_queue(), {
            ViewHelper.showToast(NSLocalizedString("RECORDING", comment: ""))
            self.recordAudioButton.imageView!.image = UIImage(named: "RecordAudioClicked")
        })
    }

    func onRecordAudioStop() {
        dispatch_async(dispatch_get_main_queue(), {
            self.recordAudioButton.imageView!.image = UIImage(named: "RecordAudio")
        })
    }

    func onRecordAudioFinished() {
        HttpPostHelper.messageAudio(partnerUserId: partnerUserId)
    }

    func playAudioFromUrl(sender: UIButton) {
        let messageId = messages[sender.tag].id
        audioHelper.playAudioMessageFromUrl(messageId)
    }

}
Stefan Salatic

放在下面super.init()

该对象需要首先由超类初始化,然后您可以进行自定义初始化。

override init() {
    super.init()
    setupAudioSession()
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

'在super.init初始化self之前在方法调用中使用self',无法通过方法调用来初始化属性

来自分类Dev

Swift:便捷初始化程序-在self.init调用之前使用的Self

来自分类Dev

Swift类中的错误:super.init调用时未初始化属性-如何初始化需要在其初始值设定项参数中使用self的属性

来自分类Dev

super.init调用未初始化属性“ self。*”

来自分类Dev

Swift 2.0:在存储属性初始化之前使用self in方法调用

来自分类Dev

在super.init之前的表达式中使用初始化属性的Swift错误

来自分类Dev

在“super.init”调用之前在方法调用“foo”中使用“self”

来自分类Dev

从NSObject继承对象导致错误在super.init调用中未初始化属性'self._username'

来自分类Dev

迅速在super.init调用中未初始化属性“ self.title”

来自分类Dev

迅速在super.init调用中未初始化属性“ self.title”

来自分类Dev

Swift在静态方法中初始化Self

来自分类Dev

属性'self.myDelegate'未在super.init中初始化-委托

来自分类Dev

Swift:在init中调用self方法

来自分类Dev

Swift:在init内调用self方法

来自分类Dev

Swift 5.1 @propertyWrapper-在初始化所有存储的属性之前在属性访问中使用“自我”

来自分类Dev

即使在保护自我和非可选属性之后,也会获得“在初始化之前使用的变量‘self.xxx’”

来自分类Dev

在super.init调用之前使用“自我”

来自分类Dev

Swift中的UIViewController初始化引发编译错误

来自分类Dev

初始化程序使用swift 3进行自我调用

来自分类Dev

Swift编译错误,使用super.init(nonretainedObject :)子类化NSValue

来自分类Dev

Swift编译错误,使用super.init(nonretainedObject :)子类化NSValue

来自分类Dev

在Swift中NSObject子类的初始化程序中调用super.init()

来自分类Dev

Swift:属性未在super.init调用中初始化

来自分类Dev

在init()中初始化2个变量:'self'在初始化所有存储的属性之前使用

来自分类Dev

Swift懒惰使用self实例化

来自分类Dev

Swift懒惰使用self实例化

来自分类Dev

SwiftUI“无法在属性初始化程序中使用实例成员'numberOfDevice';属性初始化程序在'self'可用之前运行”错误

来自分类Dev

NSViewController的子类:在self.init被称为Error之前委托初始化程序使用'self'

来自分类Dev

super(ClassName,self)._ init_()的用途是什么

Related 相关文章

  1. 1

    '在super.init初始化self之前在方法调用中使用self',无法通过方法调用来初始化属性

  2. 2

    Swift:便捷初始化程序-在self.init调用之前使用的Self

  3. 3

    Swift类中的错误:super.init调用时未初始化属性-如何初始化需要在其初始值设定项参数中使用self的属性

  4. 4

    super.init调用未初始化属性“ self。*”

  5. 5

    Swift 2.0:在存储属性初始化之前使用self in方法调用

  6. 6

    在super.init之前的表达式中使用初始化属性的Swift错误

  7. 7

    在“super.init”调用之前在方法调用“foo”中使用“self”

  8. 8

    从NSObject继承对象导致错误在super.init调用中未初始化属性'self._username'

  9. 9

    迅速在super.init调用中未初始化属性“ self.title”

  10. 10

    迅速在super.init调用中未初始化属性“ self.title”

  11. 11

    Swift在静态方法中初始化Self

  12. 12

    属性'self.myDelegate'未在super.init中初始化-委托

  13. 13

    Swift:在init中调用self方法

  14. 14

    Swift:在init内调用self方法

  15. 15

    Swift 5.1 @propertyWrapper-在初始化所有存储的属性之前在属性访问中使用“自我”

  16. 16

    即使在保护自我和非可选属性之后,也会获得“在初始化之前使用的变量‘self.xxx’”

  17. 17

    在super.init调用之前使用“自我”

  18. 18

    Swift中的UIViewController初始化引发编译错误

  19. 19

    初始化程序使用swift 3进行自我调用

  20. 20

    Swift编译错误,使用super.init(nonretainedObject :)子类化NSValue

  21. 21

    Swift编译错误,使用super.init(nonretainedObject :)子类化NSValue

  22. 22

    在Swift中NSObject子类的初始化程序中调用super.init()

  23. 23

    Swift:属性未在super.init调用中初始化

  24. 24

    在init()中初始化2个变量:'self'在初始化所有存储的属性之前使用

  25. 25

    Swift懒惰使用self实例化

  26. 26

    Swift懒惰使用self实例化

  27. 27

    SwiftUI“无法在属性初始化程序中使用实例成员'numberOfDevice';属性初始化程序在'self'可用之前运行”错误

  28. 28

    NSViewController的子类:在self.init被称为Error之前委托初始化程序使用'self'

  29. 29

    super(ClassName,self)._ init_()的用途是什么

热门标签

归档