Author: fengsh998 Original address:http://blog.csdn.net/fengsh998/article/details/32715833 Reprint Please indicate the source Assuming that the article is helpful to you, please leave a message or follow the public account fengsh998 to support me, thank you!
Although Swift is a new language, it retains a number of OC mechanisms, which make swift and OC better fused together. Assume that there is no OC basis for Google first.
such as: Kvo. Delegate. Notification.
See demo.
Import FOUNDATION@OBJC//need to open OBJC identity, otherwise @optional compile error protocol Kvodemodelegate {func willdosomething () @optional func did DoSomething ()//optional Implementation,}let ntfname = "Test_notification" class Kvodemo:nsobject//Do not write NSObject default is nsobject from {var deleg ate: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.post Notificationname (Ntfname, Object:nil, Userinfo:nil)} deinit {}} Test:
Class Viewcontroller:uiviewcontroller,kvodemodelegate {//kvo override func Observevalueforkeypath (keypath:str ING, 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 w Ill do it. ")} Func diddosomething () {println ("I had do it.") }//notification func onrecvicenotification (notification:nsnotification) {println ("Recevice notificat ION \ (Notification)}} override Func Viewdidload () {super.viewdidload ()//Do any additional setup a fter 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 = Nsnotification Center.defaultcenter () Ntf.addobserver (self, selector: "Onrecvicenotification:", Name:ntfnaMe, Object:nil) kvo.notificationpost () Ntf.removeobserver (self)}
Results:
The new value is 280i would 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}
Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.
Initial Swift Language learning note 8 (reserved for many OC implementations)