Learn more about how VC switching is transmitted in iOS

Source: Internet
Author: User

Since the last interview mentioned the relevant content, so this time I specifically study the iOS several ways:
First, all the values are listed, if there are omissions, please correct

First list the methods used in iOS:

    1. Init value (that is, the parameters of the response are set when the VC is created)
    2. Property transfer value (that is, attribute assignment)
    3. Router value (this is used in OC because the author does not write the Swift version, so first open a hole, it is estimated that I will pits)
    4. Delegate Pass value (via protocol and proxy)
    5. Closure (block) transfer value (via closure in Swift, similar to block pass in OC)
    6. Notification value (pass value via message center)
    7. KVO Pass value (pass through the Observer mode)
    8. Appdelegate values are transmitted by appdelegate
    9. Nsuserdefault Pass Value via Nsuserdefault
    10. Storage of global variables via static, no demo is done here

Basically summed up is the above 10 kinds, next I will be a kind of introduction, at the same time will explain the value of the way encountered in the pit.

All the code in this article has been put on GitHub, I'll add the GitHub address at the end of the article, so I'll just show the main code in the article.

First, the value of the Init

This is simply explained by invoking the custom init function when the VC object is init, so that the required parameters are passed in to the corresponding object.

The implementation code is as follows:

//源VCfunc jumpToNextVC() {    goal = TVGoalViewController.init(text: self.input.text!)    navigationController?.pushViewController(goal, animated: true)}//目标VCconvenience init(text:String) {    self.init(nibName:nil, bundle:nil)    self.text.texttext}

Obviously, this method of transmission has a high coupling, the maintenance of the latter has a certain impact, so the individual does not recommend. (although I was in the beginning to write code, it is not so dry face ~ ~)

Second, property transfer value (that is, attribute assignment value)

The property value is copied separately for each attribute in the VC after the VC is created.

//源VC:func jumpToNextViewController() {    let goal = TVGoal2ViewController()    goal.showlabel.text = self.input.text    self.navigationController?.pushViewController(goal, animated: true)}

Advantages and Disadvantages: Although the coupling is decoupled compared to the previous one, it is necessary to set the corresponding attribute in the target VC to public in order to be assigned in the original VC, which has a certain effect on the security of the code.

Third, the Router pass value

This way in OC has a certain use, but relatively unpopular, the main way through a separate class to save all the VC needs to jump, while the value is stored in the corresponding params. Thus, the class is transformed by the function of the class, because the original author has only the OC version, so the OC code is not affixed here, and it is estimated that I will be porting this function to Swift over the next few days.

Pros and Cons: Because of the class to save the required content, so it is decoupled, but because of the introduction of third-party classes, so the operation is relatively cumbersome, and need to learn the third-party framework functions, so there is a certain cost of learning.

Iv. Delegate Transmission Value

This approach is one of the more common approaches in iOS development, and Apple's official use of this method, such as Appdelegate, is extensive. This method is also used frequently in Uitextfield,uiscrollview and other controls to pass values.

Apple's official delegate has the following explanations:

Delegation is a simple and powerful pattern in which one object in a program 1 acts on behalf of, or in coordination with, Another object. The delegating object keeps a reference to the other object-the Delegate-and at the appropriate time sends a message to it . The message informs the delegate of an event, the delegating object is about to handle or have just handled. The delegate respond to the message by updating the appearance or state of itself or other objects in the application, And in some cases it can return a value this affects how an impending event is handled. The main value of delegation is the it allows-easily customize the behavior of several objects in one central Obje Ct.

The code is as follows:

//Original VC fileProtocol Logindelegate {func changetext (name:string)}class Tvloginviewcontroller:Uiviewcontroller{@IBOutletWeakvar label:uitextfield! @IBOutletWeakvar Loginbutton:UIButton!    var delegate:logindelegate? Override Func Viewdidload () {Super. Viewdidload() Self. Loginbutton. AddTarget( Self, Action:#selector (Clicklogin), forControlEvents:UIControlEvents.TouchUpInside)} func Clicklogin () { Self. Delegate?. Changetext( Self. Label. Text!) Self. Navigationcontroller?. popviewcontrolleranimated(true)    }}//target VC fileClass Tvdelegateviewcontroller:Uiviewcontroller, logindelegate{@IBOutletWeakvar WelcomeLabel:UILabel! @IBOutletWeakvar login:UIButton! Override Func Viewdidload () {Super. Viewdidload() Login. AddTarget( Self, Action:#selector (Next), ForControlEvents:UIControlEvents.TouchUpInside)} func Changetext (name:string) { Self. WelcomeLabel. Text="Welcome back:"+name} func Next () {Let goal = Tvloginviewcontroller () goal. Delegate= Self         Self. Navigationcontroller?. Pushviewcontroller(Goal, Animated:true)    }}

Pros and Cons: Personally, I am more optimistic about the value of delegate, because of his obvious structure, clear syntax definition, reduce maintenance costs, strong code readability. At the same time, reduce the coupling of the code, so that event monitoring and event processing phase separation. You do not need to create a third party to listen for events and transfer data. and a controller can implement multiple agents, to meet the custom development requirements, optional must have greater flexibility. However, due to the need to create a protocol, and then encode, it may be a larger code size.

Five, closed packet transmission value

The closure value is similar to the block pass value in OC. And Apple's official explanation for block is this:

A block is an anonymous inline collection of code, and sometimes also called a "closure".
Blocks is a powerful c-language feature that's part of COCOA application development. They is similar to ' closures ' and ' lambdas ' you'll find in scripting and programming languages such as Ruby, Python, and Lisp. Although the syntax and storage details of blocks might at first glance seem cryptic, you'll find that it ' s actually quite Easy to incorporate blocks into your projects ' code.

This shows that the closure in the actual use of a large use of surface, not only in OC, in the Ruby,python,lisp are used. And because the amount of code needed to implement it is less than delegate, many people like it (but I don't like it much).
The code is as follows:

//Original VC file:Typealias returnclosure=(string:String) -Void...Func login () {ifClosurevalue!=Nil {Closurevalue!(string: Self.Input.Text!)    } Self.Navigationcontroller?.Popviewcontrolleranimated (true)}//target VC fileFunc Myclosure (string:String) -Void{ Self.WelcomeLabel.Text= "Welcome:"+string}func Jump () { LetGoal=Tvlogin1viewcontroller () goal.Closurevalue=Myclosure Self.Navigationcontroller?.Pushviewcontroller (goal, animated:true)}
VI. notification value of the transmission

Notification, like the above delegate, is often used in iOS development by using the Observer pattern in design mode, but when one of the contents changes, it accepts the content change by Notificationcenter. To tell the person who needs to be told, the original value has changed.

The code is as follows:

//Original VC file:Func Logyouname () {Let notific =nsnotification. Init(Name:"Loginnamenotification", object: Self, UserInfo: ["Name": Name. Text!])Nsnotificationcenter. Defaultcenter(). Postnotification(notific) Self. Navigationcontroller?. popviewcontrolleranimated(true)}//target VC file:Func Next () {Let goal = Tvlogin2viewcontroller ()Nsnotificationcenter. Defaultcenter(). Addobserver( Self, selector:#selector (loginName), Name: "Loginnamenotification", Object:goal)     Self. Navigationcontroller?. Pushviewcontroller(Goal, Animated:true)}func loginName (notification:nsnotification) {Let DIC = notification. UserInfo     Self. Welcomebutton. Text="Welcome:"+ (String) (dic!["Name"]!)Nsnotificationcenter. Defaultcenter(). Removeobserver( Self)}

Pros and Cons: Notificatoin uses the Observer pattern in design mode, which has the advantage of being simple to use and thin in code. At the same time, it solves the problem of listening to multiple objects simultaneously, which is very convenient when we need to invoke the modified content.

Vii. KVO value of the transmission

This method of transmitting value and notification is basically consistent, and is realized by the observer pattern in the design pattern. However, the difference is that in general notification is a third party as a singleton to implement, and KVO is directly through an object to see whether the value of another object has changed, the observer itself and the observer is not necessarily the VC, as long as it is inherited nsobject can implement the method.

The code is as follows:

//Original VC fileFunc login () { Self. SetValue(Input. Text, Forkey:"username") Self. Navigationcontroller?. popviewcontrolleranimated(true)}//target VC file:Override Func Viewdidload () {Super. Viewdidload() Loginbutton. AddTarget( Self, Action:#selector (login), forControlEvents:UIControlEvents.TouchUpInside)Goal. Addobserver( Self, Forkeypath:"username", Options: [Nskeyvalueobservingoptions. New, nskeyvalueobservingoptions. old], Context:Nil}override func Observevalueforkeypath (keypath:string, Ofobject object:anyobject?, change: [String:anyobject]?, cont ext:unsafemutablepointer<void>) {ifKeyPath = ="username"{ Self. WelcomeLabel. Text="Welcome"+ (String) ((change!) ["New"]!) }}

Advantages and Disadvantages: advantages and disadvantages and notification, but in this case there is a pit, when you input the corresponding text in input, you need to click on the log, the content in the text to save, Because the observer does not observe the contents of the Uitextfield, there is a good chance that the problem will occur. (It is not recommended for individuals to use this method to observe variables that need to be entered manually)

Eight, Appdelegate pass value

This approach is based on the actual creation of the iOS app, evoking the entire app through Appdelegate, so that appdelegate can manipulate the entire app, and as a total control, all internal classes can be uiapplication to get delegate , thus getting appdelegate. So it is possible to transfer the value through him.
The code is as follows:

Source VC file Func next () {Let next = Tvgoal3viewcontroller () Let selfdelegate = UIApplication. Sharedapplication(). Delegateas! Appdelegate selfdelegate. storestring= Self. Input. Text! Self. Navigationcontroller?. Pushviewcontroller(Next, Animated:true)} Target VC file override func Viewdidload () {Super. Viewdidload() Let app = UIApplication. Sharedapplication() Let Selfdelegate = App. Delegateas! Appdelegate ShowLabel. Text= Selfdelegate. storestringSelf. Backbutton. AddTarget(Self, Action:#selector (goBack), forControlEvents:UIControlEvents.TouchUpInside)}

Advantages and disadvantages: Because through the appdelegate to achieve, basically the contents are saved in the appdelegate, so it is convenient to call, because all kept in there, resulting in the entire appdelegate appear bloated, inconvenient and later maintenance.

Nine, Nsuserdefault pass value

Apple provides developers with a NSUSERDEFAULT system variable that developers can use to save content throughout the system, making it easy to make the next call, which is similar to appdelegate.
The code is as follows:

//源文件NSUserDefaults.standardUserDefaults().setObject(self.input.text"store")//目标文件let userdefault = NSUserDefaults.standardUserDefaults()self.showLabel.text = (String)(userdefault.valueForKey("store")!)

Pros and Cons: The main and appdelegate, but because it is a system-level variable, so he gave us the memory space is limited, can not store too much information. (Remember to store the synchronization, easy to continue to use later)

X. Global variable static pass value

This is the same as in the general language, because static exists in the global store (static storage), and as long as the program does not exit, it will be saved. One of the benefits is that you can use it repeatedly, but because it is not released, so if the amount of a large, prone to memory shortage ~ ~ ~ So it is not recommended.

Summary: The above is all 10 kinds of iOS common values, they have each of the advantages, shortcomings, so specifically how to use, or need to identify the developers themselves.

And finally the GitHub address.

Learn more about how VC switching is transmitted in iOS

Related Article

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.