單例
class TheOneAndOnlyKraken {
// 存儲屬性
var name : String?
var age : Int = 0
static let sharedInstance = TheOneAndOnlyKraken()
// 防止外部調用
private init() {} //This prevents others from using the default '()' initializer for this class.
}
TheOneAndOnlyKraken.sharedInstance
代理傳值
- B需要代理,聲明以及聲明方法
func eatMany(food1: String) -> Void
protocol EatFoodDelegate {
func eatMany(food1: String) -> Void
}
// 第一種設置代理方式
extension ViewController : EatFoodDelegate{
func eatMany(food1 : String) -> Void {
print(food1)
}
}
// 第二種設置代理方式, 逗號 + 代理協議
// class ViewController: UIViewController, EatFoodDelegate
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print("觸摸屏幕")
let vcOne = TestOne()
// 設置代理
vcOne.delegate = self
vcOne.strBlock = {(str1 : String, str2 : String) -> Void in
print(str1 + str2)
}
self.present(vcOne, animated: true) {
print("跳轉完成")
}
}
閉包傳值
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print("觸摸屏幕")
let vcOne = TestOne()
// 實現閉包 處理回調
vcOne.strBlock = {(str1 : String, str2 : String) -> Void in
print(str1 + str2)
}
self.present(vcOne, animated: true) {
print("跳轉完成")
}
}
- 控制器B
- 聲明閉包類型
- 兩個字符串參數, 返回空類型
?
延遲初始化
var strBlock : ((_ str1 : String, _ str2 : String) -> Void)?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// self.dismiss(animated: true) {
// print("控制器消失了")
// }
// 對於當前沒有進行初始化的對象選擇了optional 即 ? 延遲初始化,需要解包時
// ! 感嘆號解包如果對象為空nil Unexpectedly found nil while unwrapping an Optional value
// ? 問號解包 對象為空不崩潰 -建議用?
strBlock?("hello", "world")
let dic = ["name" : "張三", "age" : 18] as [String : Any]
NotificationCenter.default.post(name : NSNotification.Name.init(rawValue: "h"), object: dic)
}
發送通知
- 注冊通知 & 接收通知
- 方法必須是
oc
方法 @objc
前綴修飾
- 通知名字
NSNotification.Name(rawValue: "h")
// 添加通知實現同時方法
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.hello), name: NSNotification.Name(rawValue: "h"), object: nil)
}
@objc func hello() -> Void{
print("hello")
}
- 發送通知
- 通知名字
NSNotification.Name.init(rawValue: "h")
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.dismiss(animated: true) {
print("控制器消失了")
}
NotificationCenter.default.post(name : NSNotification.Name.init(rawValue: "h"), object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}