首页 > 代码库 > 初探swift语言的学习笔记八(保留了许多OC的实现)
初探swift语言的学习笔记八(保留了许多OC的实现)
尽管swift作为一门新语言,但还保留了许多OC的机制,使得swift和OC更好的融合在一起。如果没有OC基础的先GOOGLE一下。
如:KVO,DELEGATE,NOTIFICATION。
详见DEMO。
import Foundation @objc // 需要打开objc标识,否则@optional编译出错 protocol kvoDemoDelegate { func willDoSomething() @optional func didDoSomething() //可选实现, } let ntfname = "test_notification" class kvoDemo : NSObject //不写NSObject默认就是从NSObject来的 { var delegate: kvoDemoDelegate! var presult : Double = 0.0 var result : Double { get{ return presult; } set{ self.presult = newValue } } init() { } func doSomething() { if let yet = self.delegate? { delegate!.willDoSomething() } for _ in 1..5 { println("i‘m doing now,don‘t touch me,please.") } if let yet = self.delegate? { delegate!.didDoSomething!() } } func notificationPost() { let ntf = NSNotificationCenter.defaultCenter() ntf.postNotificationName(ntfname, object :nil, userInfo:nil) } deinit { } }测试:
class ViewController: UIViewController,kvoDemoDelegate { //KVO override func observeValueForKeyPath(keyPath: String?, ofObject: AnyObject?, change: NSDictionary?, context: CMutableVoidPointer) { if keyPath == "result" { var newvalue : AnyObject? = change?.objectForKey("new"); println("the new value is \(newvalue)") } } //delegate func willDoSomething() { println("i will do it.") } func didDoSomething() { println("i had do it.") } //notification func onRecviceNotification(notification:NSNotification) { println("Recevice notification \(notification)") } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. var kvo = kvoDemo() kvo.addObserver(self, forKeyPath: "result", options: NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old, context: nil) kvo.result = 280.0 kvo.removeObserver(self,forKeyPath:"result",context: nil) kvo.delegate = self kvo.doSomething() let ntf = NSNotificationCenter.defaultCenter() ntf.addObserver(self, selector:"onRecviceNotification:", name :ntfname, object : nil) kvo.notificationPost() ntf.removeObserver(self) } }
结果:
the new value is 280 i will do it. i‘m doing now,don‘t touch me,please. i‘m doing now,don‘t touch me,please. i‘m doing now,don‘t touch me,please. i‘m doing now,don‘t touch me,please. i had do it. Recevice notification NSConcreteNotification 0x10be60930 {name = test_notification}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。