没有可访问的初始化者,Swift Singleton

时间:2015-01-18 00:48:50

标签: swift delegates singleton

更新

刚试图删除

init(delegate: MPPlayerDelegate) {
self.delegate = delegate
}

按照我的说法做了

var updateLabel: MPPlayerDelegate = MPPlayerSingleton()

在UIVIewcontroller.swift

但仍然是一个问题。      MPPlayerDelegate没有名为delegate的成员

我正在尝试使用委托构建一个单例,以便它可以使用从http流中获取的信息更新uilabel" Radio"

我收到错误

无法构建MPPlayerDelegate,因为它没有可访问的初始化程序

MPPlayerSingleton.swift

 @objc protocol MPPlayerDelegate{
func updateLabel(artist: String, title: String)

}


public class MPPlayerSingleton : NSObject, MPPlayerDelegate {

var delegate: MPPlayerDelegate?

init(delegate: MPPlayerDelegate) {
    self.delegate = delegate


}


let songInfo = NSMutableDictionary()
var moviePlayer = MPMoviePlayerController()
var uiView = UIView()

var informationMetaTitle: String!
var informationMetaArtist: String!

class var shared: MPPlayerSingleton {

    struct Static {
        static var instances: MPPlayerSingleton?
        static var token: dispatch_once_t = 0

    }
    dispatch_once(&Static.token) {
        Static.instances = MPPlayerSingleton(delegate: MPPlayerDelegate())  // **This is where the error is** 
    }

    return Static.instances!
}



func updateLabel(artist: String, title: String) {

}

UIViewController.swift

var updateLabel: MPPlayerDelegate = MPPlayerDelegate() // **same error here**
    updateLabel.delegate = self // says there is no delegate 

2 个答案:

答案 0 :(得分:1)

您获得的错误与单身人士无关,他们是因为您正在尝试创建协议实例,这是不可能的。您可以使用协议声明属性作为其类型,但在创建要分配给该属性的实例时,您需要使用符合给定协议的实际类。

你的协议声明没问题:

@objc protocol MPPlayerDelegate {
    func updateLabel(artist: String, title: String)
}

MPPlayerSingleton课程中,您不希望初始化程序具有委托,因为这需要由您的客户端代码设置。摆脱它,NSObject的空init()将可用,解决您的大部分问题:

public class MPPlayerSingleton : NSObject, MPPlayerDelegate {
    var delegate: MPPlayerDelegate?
    // ...

    // Cleaned-up singleton  
    class var shared: MPPlayerSingleton {
        struct Static {
            static var instance = MPPlayerSingleton()
        }
        return Static.instance
    }
}

现在您可以将delegate设置为您的一个视图控制器,这是您在这种情况下可能需要的内容:

class MyViewController: UIViewController, MPPlayerDelegate {
    override func viewDidLoad() {
        MPPlayerSingleton.shared.delegate = self
    }

    // MARK: - MPPlayerDelegate

    func updateLabel(artist: String, title: String) {
        // ...
    }
}

答案 1 :(得分:0)

我猜你的意思是:

var updateLabel: MPPlayerDelegate = MPPlayerSingleton()