iOS parsing of Uiviewcontroller life cycle and attribute methods

Source: Internet
Author: User

iOS parsing of Uiviewcontroller life cycle and attribute methodsFirst, Introduction

As an MVC design model, C,controller has been playing the most important role in project development, which is a bridge between view and data, which is managed to show the data in our view layer. Uiviewcontroller in iOS is one of the most basic classes in the Uikit framework. From the first UI view to the complex complete project, Uiviewcontroller is essential. The Uiviewcontroller-based package and extension also provides a great variety of complex interface logic. This blog, designed to discuss Uiviewcontroller's life cycle and attribute approach, often gets unexpected surprises on most basic things.

Second, the life cycle of Uiviewcontroller

To understand Uiviewcontroller, we must first clarify its life cycle. In object-oriented language, it is the object, it must have the life cycle, Uiviewcontroller is no exception, life cycle Management Controller's scope and time, also manages the scope and time of its objects. First, there are several functions in Uiviewcontroller that are related to their life cycle:

Class initialization method + (void) initialize;//Object Initialization Method-(Instancetype) init;//initialization from archive-(Instancetype) Initwithcoder: (Nscoder *) coder;/ /Load View-(void) loadview;//will load View-(void) viewdidload;//will layout child view-(void) viewwilllayoutsubviews;//already layout child view-(void) viewdidlayoutsubviews;//Memory Warning-(void) didreceivememorywarning;//has been shown-(void) Viewdidappear: (BOOL) animated;//will show-( void) Viewwillappear: (BOOL) animated;//will disappear-(void) Viewwilldisappear: (BOOL) animated;//has disappeared-(void) viewdiddisappear :(BOOL) animated;//is released-(void) dealloc;

With so many functions above, at first glance what is complicated, what is the clarity of the relationship, except that the Initialize,init and Initwithcoder are not in the declaration cycle of all objects, other functions are called sequentially in the Uiviewcontroller declaration cycle. So what is the specific sequence of calls, the best way is to practice, by the number of printing, the results are as follows:

This is a viewcontroller complete declaration cycle, in fact there are a lot of places we need to pay attention to:

The 1:initialize function is not called every time the object is created, it is called only when the class is created for the first time, some classes are prepared, the object of the class is created again, and the Initalize method will not be called, for subclasses of this class, If the Initialize method is implemented, the subclass will call its own Initalize method the first time the object is created, and then it will not be called, and if it is not implemented, its parent class would call its own initialize method again, and no further creation would be invoked. So, if we have some global variables associated with this, we can initialize them here.

The 2:init method is similar to the Initcoder method, except that the environment being called is different, and if it is initialized with code, Init is called, and initialization from the nib file or archive is called Initcoder.

The 3:loadview method is the starting method to begin loading the view, unless it is called manually, otherwise it will only be called once in the life cycle of the Viewcontroller.

The 4:viewdidload method is our most commonly used method, the initialization of the member objects and variables in the class we will put in this method, after the class is created, regardless of the view's presentation or disappearance, this method will only be called once when the layout is going.

5:viewwillappare: Called when the view is going to be displayed.

6:viewwilllayoutsubviews: Called after Viewwillappare, the child view will be laid out.

7:viewdidlayoutsubviews: The layout has completed the child view.

8:viewdidappare: Called when the view finishes displaying.

9:viewwilldisappare: Called when the view is going to disappear.

10:viewdiddisappare: Called when the view has disappeared.

Called when the 11:dealloc:controller is released.

Note: After testing, the controller loaded from the nib file, as long as it is not released, will call the Layoutsubviews method every time Viewwillappare Sometimes even after the viewdidappare is called once layoutsubviews, but the emphasis is loaded from the code will only start the call once, and then not, so note that writing the relevant layout code in Layoutsubviews is very dangerous.

Third, load the Uiviewcontroller instance from the storyboard to pass the value trap

We know that when we load Viewcontroller from storyboard, the view that we drag and drop in the controller can be initialized, and there is one thing we need to be aware of, if we need to set the value of the view in the controller, The view has not been created by initialization in the controller that is obtained by the following method:

ViewController2 * ViewController2 = [[Uistoryboard storyboardwithname:@ "Main" Bundle:[nsbundle Mainbundle]] instantiateviewcontrollerwithidentifier:@ "ViewController2"];

We can pull a label in ViewController2 's storyboard and then link to the header file, print as follows, and we'll find that when we get the controller, the view object inside is not created:

ViewController2 * ViewController2 = [[Uistoryboard storyboardwithname:@ "Main" Bundle:[nsbundle Mainbundle]]    instantiateviewcontrollerwithidentifier:@ "ViewController2"];    NSLog (@ "%@", Viewcontroller2.label); [Self presentviewcontroller:viewcontroller2 animated:yes completion:nil];

Print as follows:

As you can imagine, if we need to set some property on the label at this time, it will fail. It is suggested that you can manually tune the following Loadview methods after creation, and we will try the results as follows:

As you can see, after manually calling Loadview, the label is created, but there is a more serious problem, the system is not calling the Viewdidload method, which is very risky, because most of our initialization code will be placed in this method, So calling Loadview manually is a bad way, and the Apple documentation declares that for the Loadview method, we never call it manually, so how do we implement the value setting for the member object after creation, and add a method to the iOS9:

-(void) loadviewifneeded Ns_available_ios (9_0);

This method is useful, and invoking this method will create the view and will not ignore the viewdidload call.

In IOS9, Uiviewcontroller also adds the following Boolean attribute, which can be used to determine if the controller's view has been loaded:

@property (Nullable, Nonatomic, ReadOnly, strong) UIView *viewifloaded Ns_available_ios (9_0);
Iv. related mutual methods of Uiviewcontroller and Stroyboard

For Viewconroller, we generally have two ways to create, one is to use pure code, one is associated with storyboard, in Uiviewcontroller, there are many ways to facilitate our interaction with storyboard.

1, Viewcontroller directly in the storyboard to jump the value of the transfer

In the storyboard interface jump is very convenient, we pull in the storyboard two Viewcontroller, add a button on the top, click the button control, pull the mouse to the second controller, The following jump options appear:

Once we have chosen one, a jump connection is established between the two controllers. When we run the click button, we will automatically jump from the first controller to the second controller. The following methods can be used to control whether a jump is Uiviewcontroller:

-(BOOL) Shouldperformseguewithidentifier: (NSString *) identifier sender: (nullable ID) sender Ns_available_ios (6_0);

If this method returns no, the automatic jump will not be able to proceed, will be rejected, it should be noted that this method will only be called when the automatic jump, we manually use the code to jump storyboard in the connection relationship is not called, we discussed later.

After executing the above method, if return yes, the system will also perform the following method, as a pre-jump preparation, we can do some value-added operation in this method, whether let us manually jump or storyboard in the automatic jump, will be executed:

-(void) Prepareforsegue: (Uistoryboardsegue *) Segue Sender: (nullable ID) sender Ns_available_ios (5_0);

The Sugur object encapsulates the relevant Viewcontroller, and you can use the Segue.destinationviewcontroller get.

Segue in Storyboard In addition to the automatic forward jump, we can also reverse the jump, similar to pop and dismiss method, this segue is called unwind Sugue. For example, we have a controller1 and a controllert2, to use unwind segue from 2 to return 1, we need to implement the following format in the 2 method:

-(Ibaction) Unwindseguetoviewcontroller: (Uistoryboardsegue *) Segue {NSLog (@ "Unwindseguetoviewcontroller");}

The return value in this method must be ibaction, the parameter must be Uistoryboardsegue, the method name can be defined by itself, and then in the exit option in ViewController1 in storyboard, We'll find one more way to do this:

We can connect it to a button on the ViewController2:

This way, when we click on the button in ViewController2, we will return to our first ViewController1.

Of course, when using the unwind segue method, there will be some callbacks to help us to set the pre-jump and pass the value, Uiviewcontroller the following method will be called before the jump, return no, you cannot jump:

-(BOOL) Canperformunwindsegueaction: (SEL) Action Fromviewcontroller: (Uiviewcontroller *) Fromviewcontroller    Withsender: (ID) sender{NSLog (@ "canperformunwindsegueaction"); return YES;}

We will then execute our custom Unwindsegue method, in which we can write nothing and the pattern will jump.

2. Use code to jump controller in storyboard

We can also use the code to jump the Segue connection in the storyboard, except that we can lalacheche the controller in storyboard.

To establish a segue connection between the two controllers in the storyboard, we can take a name:

In the method that triggers the jump, use the following method to jump, this parameter ID is we get Segue ID:

-(void) Performseguewithidentifier: (NSString *) identifier sender: (nullable ID) sender Ns_available_ios (5_0);

The following three properties we can obtain the controller's nib file name, its storyboard and its bundle:

@property (Nullable, Nonatomic, ReadOnly, copy) NSString *nibname; @property (Nullable, Nonatomic, ReadOnly, strong) NSBundle *nibbundle; @property (Nullable, Nonatomic, ReadOnly, strong) Uistoryboard *storyboard Ns_available_ios (5_0);
V. Some affiliation between the Uiviewcontroller

This part of the content and methods may not be used in many of our contacts, but in some cases, the use of these methods can greatly facilitate some logic.

1, Parentviewcontroller

Uiviewcontroller contains an array, which can hold its sub-viewcontroller, the example used in the system is navigation and tabbar such controllers, we use the following methods to directly access the parent controller:

@property (nullable,nonatomic,weak,readonly) Uiviewcontroller *parentviewcontroller;
2. The controller's subordinate in the modal jump

When we go to the controller jump, as long as the controller is not released, we can follow the clues to find it, using the following two methods:

Its present contller, for example, A and B two controller,a jump to B, then a presentedviewcontroller is B@property (nullable, Nonatomic, ReadOnly) Uiviewcontroller *presentedviewcontroller Ns_available_ios (5_0);//And the above method is just the opposite, for example, A and B two controller,a jump to B, Then B's Presentingviewcontroller is A@property (nullable, nonatomic,readonly) Uiviewcontroller *presentingviewcontroller Ns_available_ios (5_0);

understand the above method we can know, for the reverse value of the problem, we do not need a proxy, block, notification and other such complex means, only need to get a controller to jump to it, directly set up. For example, we need to change the color of the first interface after the second interface disappears, only the following code is required in the second controller :

Self.presentingViewController.view.backgroundColor = [Uicolor colorwithred:arc4random ()%255/255.0 green:arc4random    ()%255/255.0 blue:arc4random ()%255/255.0 alpha:1]; [Self dismissviewcontrolleranimated:yes completion:nil];
Six, Uiviewcontroller modal jump and animation effects

In pure Uiviewcontroller, we use the most of the following two methods, one to jump forward, and one to return backwards:

-(void) Presentviewcontroller: (Uiviewcontroller *) viewcontrollertopresent animated: (BOOL) flag completion: (void (^ __ Nullable) (void)) Completion Ns_available_ios (5_0);-(void) dismissviewcontrolleranimated: (BOOL) Flag completion: ( void (^ __nullable) (void)) Completion Ns_available_ios (5_0);

From the method, we can see that there is animated this parameter, to choose whether there are animation effects, the default animation effect is like a drawer up from the bottom of the phone screen up, of course, this effect we can set, Uiviewcontroller like the next property to set animation effects:

@property (nonatomic,assign) uimodaltransitionstyle Modaltransitionstyle Ns_available_ios (3_0);

Note that this is going to be set to the controller that will jump to, enumerate the following:

typedef ns_enum (Nsinteger, uimodaltransitionstyle) {uimodaltransitionstylecoververtical = 0,//default, overwriting UIModalTra from bottom up Nsitionstylefliphorizontal,//Horizontal flip uimodaltransitionstylecrossdissolve,//dissolve Uimodaltransitionstylepartialcurl, Page up from bottom up};

In addition to the effect of the jump, there is also a property to set the pop-up controler fill effect, but this property is only valid on the pad, on the iphone is not valid, are filled to the entire screen:

@property (nonatomic,assign)  uimodalpresentationstyle modalpresentationstyle ns_available_ios (3_ 2);//enumeration as follows Typedef ns_enum (Nsinteger, uimodalpresentationstyle)  {         uimodalpresentationfullscreen = 0,//fills the entire screen          uimodalpresentationpagesheet,//Leave status bar          uimodalpresentationformsheet,//four-week left darkening blank          uimodalpresentationcurrentcontext ,//and jump to its controller to stay consistent          Uimodalpresentationcustom ns_enum_available_ios (7_0),//Custom          uimodalpresentationoverfullscreen ns_enum_available_ios (8_0),         uimodalpresentationovercurrentcontext ns_enum_available_ios (8_0),         uimodalpresentationpopover ns_enum_availaBle_ios (8_0)  __tvos_prohibited,        uimodalpresentationnone  ns_enum_available_ios (7_0)  = -1,         };



iOS parsing of Uiviewcontroller life cycle and attribute methods

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.