"We all love Paul Hegarty." Stanford IOS8 public class personal note 43 protecting nsnotification memory Security

Source: Internet
Author: User

In the previous demo, I explained the use of nsnotification, Nsnotification is implemented using Nsoperationqueue, so using nsnotification inevitably falls into memory problems, For example, the following scenario: Prepare two scenes in storyboard. Display a label in the first scene with a button next to it we can click this button modal segue to another scene, where a textfield is placed to enter a new name to modify the label display on the first page, which is a very common feature. The layout of the scene is as follows:

Create two controllers: Viewcontroller and Modalviewcontroller relate the first and second scenarios, respectively. You can see that the second scene is placed in the navigation controller, and put a "done" button in its upper-right corner to return.
The first scene's edit button clicks down and triggers modal segue to the second scene, the segue named Editsegue.
Associate the controller and code, set a Nametoedit property as the model in Modalviewcontroller:

weakvar nameTextField: UITextField!    weakvar nameLabel: UILabel!    var""

Because the role of scene two is to edit, I need to automatically select TextField from scene one to scene two, keyboard slide out, so the need is to add a sentence in the Modalviewcontroller Viewdidload method:

nameTextField.becomeFirstResponder()

If there are multiple TextField, choose the appropriate (generally the top) TextField become the first responder, now you transition to scene two when you see the interface as follows:

Now add the click Return to close the keyboard event, to use the Uitextfield delegate, first follow the delegate protocol:

class ModalViewController: UIViewController,UITextFieldDelegate 

Next set TextField delegate, here is a detail, do not write the delegate operation to the Viewdidload method is loaded, this is because only when the return button is clicked to call the delegate method, This allows you to implement a feature where clicking return cannot be returned if the contents of the TextField are not modified. To implement such details, you can set the delegate method for TextField in the property watcher:

var nameTextField: UITextField!{        didSet{ nameTextField.delegate = self}    }

If there are multiple TextField in the scene, each one does so. Then close the keyboard in the delegate method:

func textFieldShouldReturn(textField: UITextField) -> Bool {        textField.resignFirstResponder()        returntrue    }

Note that the Becomefirstresponder in Resignfirstresponder and viewdidload in this delegate are not necessarily corresponding, because all TextField will call this method when you click Return. So here is the first responder identity of the incoming TextField.
Now you need to add a way to modify the model, because TextField's role is to modify the model so that the UI is updated only when the model changes, so set the attribute observer in Nametoedit:

var nameToEdit:String?{ didSet{ updateUI() } }

The UpdateUI method is as follows:

 func updateUI(){   nameTextField?.text = nameToEdit    nameLabel?.text = nameToEdit    }

It is important to note that the UpdateUI () method must be assigned to a selectable type! Because in the navigation internal reason, for Segue do prepare time iboutlet may not have loaded complete, Nametextfield and Namelabel attribute is nil. Of course, the value of the model Nametoedit is the name attribute in the first scene, so the value passed in from the first scene should be displayed when scene two is first loaded, so adding this method to the Viewdidload method is also loaded:

viewDidLoad() {        super.viewDidLoad()        nameTextField.becomeFirstResponder()        updateUI()    }

In the first scenario, a value is passed to the second scene:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {        ifletas? ModalViewController{        vc.nameToEdit = name.text        }    }

If you write like this, you will find that the Nametoedit in scenario two is nil, and you may already understand the problem because Modalviewcontroller is wrapped in Navigationcontroller, So segue Destinationviewcontroller should be Navigationcontroller, there is a good way to solve this problem: the expansion of Uiviewcontroller, the method is as follows:

UIViewController{    var contentViewController:UIViewController{        ifselfUINavigationController{        return navcon.visibleViewController        else{        returnself        }    }}

Extending an attribute, if the current controller is a navigation controller, returns the first controller that it presents, and if not, returns itself, and now needs to modify the Prepareforsegue method, putting the original:

ifletas? ModalViewController

Switch

ifletas? ModalViewController

Now when you switch to scene two, both the label and the TextField have default values, which is the name in scene one. Now the problem is that when you operate the TextField will not change the actual value of the model Nametoedit, in the UpdateUI method set the label and TextField synchronization, you can see that the UpdateUI method is not called Now, Prove that the value of the model has not been modified:

At this time nsnotification will come in handy, we should modify the TextField when the real-time synchronization to modify the model:

Func Observetextfield () { LetCenter=Nsnotificationcenter.Defaultcenter () Let Queue =Nsoperationqueue.Mainqueue () Center.Addobserverforname (Uitextfieldtextdidchangenotification, Object:nametextfield,Queue:Queue) {Notificationinch        if  LetName=  Self.nametoedit{ Self.Nametoedit=  Self.Nametextfield.Text}}}

This method should be called at the right time, usually in the Viewdidappear method, not forgetting the first way to implement the parent class:

viewDidAppear(animated: Bool) {        super.viewDidAppear(animated)        observeTextField()    }

Run it again see, ok! is already a perfect MVC pattern:

Maybe you think nsnotification still have something to learn? It's so simple! Consider the following scenario: What if scenario two is removed? Because observer is in another thread, it will continue to listen to the TextField, and TextField will be removed, and the closure is always in memory, and it cannot delete itself. The procedure is to return a small cookie, as follows:

var ntfObserver:NSObjectProtocol?

The meaning of the Nsobjectprotocol type here is that it was treated as a "NSObject" object before.
Modify the Observetextfield () method to "record" it when calling the Singleton method Addobserverforname, and get the cookie it returns:

let= center.queuequeue) { notification  in        iflet=self.nameToEdit{        self.=self.nameTextField.text        }        }

Once the observation has been completed, its cookie is removed from the nsnotificationcneter and executed in another life cycle method:

override func viewDidDisappear(animated: Bool) {        super.viewDidDisappear(animated)        iflet observer = ntfObserver{        NSNotificationCenter.defaultCenter().removeObserver(observer)        }    }

Note that the optional bindings are used first, and these two life-cycle methods are ideal for doing such work. Because after MVC has been removed, we don't want to keep this object in observer's closures and let them disappear completely.
The last task is to return, add a Finish button to the navigation bar, and then associate the controller:

@IBAction func done(sender:UIBarButtonItem) {        presentingViewController?.dismissViewControllerAnimated(truecompletion:nil)    }

Because here is the test we passed in the Prepare method is a string, which is a value type, so the copy is not the original value, if you pass in a class instance, you can see that the class has been modified on return.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"We all love Paul Hegarty." Stanford IOS8 public class personal note 43 protecting nsnotification memory Security

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.