Ios-uiapplication detailed

Source: Internet
Author: User
Tags throw exception

UIApplication Introduction
    1. The UIApplication object is a symbol of the application.
    2. Each application has its own UIApplication object, and it is a singleton.
    3. The first object created after an iOS program is started is the UIApplication object.
    4. UIApplication *app = [UIApplication sharedApplication];this singleton object can be obtained by the.
    5. Some application-level operations can be performed using UIApplication objects.
UIApplication Single Example implementation principle

First we know that the UIApplication object is created in a singleton, that is, the UIApplication object is created only once in the program, and we can no longer create a new Uiapplicaiton object.
So when we try to create a new Uiapplicaiton object,
UIApplication *app = [[UIApplication alloc]init];
The program will error, let's look at the wrong message

' Nsinternalinconsistencyexception ', Reason: ' There can only be one uiapplication instance. '

Here we find that the system approach is to throw an exception that tells us that the Uiapplicaiton object can only have one.
At this point we can basically clear, Apple internal how to achieve uiapplication single case.

1. Can not call Alloc, a call to collapse, throw an exception, (the first call to Alloc will not crash, the other crashes)
2. Provide a way for the outside world to obtain a singleton (shareapplication)
3. When the program starts, create a single instance internally

Let's imitate the implementation of the system single example
Create Person class
Person.h

#import <Foundation/Foundation.h>@interface Person : NSObject//注:一般我们写单例的时候,也用shared开头,这是命名规范+(instancetype)sharePerson;@end

Person.m

#import"Person.h"@implementationPersonstatic variablesstatic person *_person =NilClass Load: Every time the program starts, all classes are loaded into memory + (void) load{_person = [[Person alloc]init];} +(Instancetype) shareperson{return _person;} + (instancetype) alloc{if (_person) { //_person value has been assigned, the outside world is not allowed to allocate memory //throw exception, tell the outside world is not allowed to assign //Create exception class //Name: Exception name //Reson: Cause of Exception //userInfo: Exception information nsexception *EXCP = [ nsexception exceptionwithname:@ " Nsinternalinconsistencyexception "Reason:@" there can only being one person instance. "UserInfo: nil]; //throw exception [EXCP raise];} return [super alloc];}  @end             

In this case, the singleton person class is implemented and throws an exception when we alloc a person to instantiate the object.

The first object created after an iOS program is started is a UIApplication object

So when did the UIApplication object be created? Then we find the entrance to the program.main.m

int main(int argc, char * argv[]) {    @autoreleasepool {        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); }}

We found that the program first returned the Uiapplicationmain method, and there were 4 parameters
Let's take a look at the introduction of these parameters
argc

The count of arguments in argv; This usually was the corresponding parameter to main.

Argv

A variable list of arguments; This usually was the corresponding parameter to main.

Principalclassname

The name of the UIApplication class or subclass. If you specify nil, UIApplication is assumed.

Delegateclassname

The name of the class from which the application delegate is instantiated. If Principalclassname designates a subclass of UIApplication, you may designate the subclass as the delegate; The subclass instance receives the Application-delegate messages. Specify nil If you load the delegate object from your application ' s main nib file.

ARGC: System or user-passed parameters
ARGV: Actual parameters passed in by the system or user

Focus on the third to fourth parameter

The third parameter, nil: Represents the UIApplication class name or subclass name nil 相当于 @"UIApplicaiton" ;
The fourth parameter: the proxy name representing the Uiapplicaiton NSStringFromClass([AppDelegate class] 相当于 @"AppDelegate" ;

At this point we can understand the process of program initiation according to the Uiapplicationmain function

  1. Creates a UIApplication object based on the passed class name, which is the first object
  2. Create the UIApplication proxy object and set the proxy for the Uiapplicaiton object
  3. Turn on Main run loop main events loop handle event to keep program running
  4. Loads the Info.plist, determines whether the specified Mian (xib or storyboard) is loaded if specified
Some application-level operations can be performed using UIApplication objects.
    • Set the red reminder number in the upper-right corner of the application icon
      @property(nonatomic) NSInteger applicationIconBadgeNumber;
      Code implementation and Effects:
      UIApplication *app = [UIApplication sharedApplication];app.applicationIconBadgeNumber = 10;// 创建通知对象UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];// 注册用户通知[app registerUserNotificationSettings:setting];

      Note: Apple in order to enhance the user experience, after iOS8 we need to create a notification to implement the icon in the upper right corner of the reminder, iOS8 before applicationIconBadgeNumber the value directly set.


Remind
  • Setting the visibility of networking indicators
    @property(nonatomic,getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
    Code implementation and Effects:
    app.networkActivityIndicatorVisible= YES;

    Networking indicator Display
  • Manage status bar
    Starting with IOS7, the system provides 2 ways to manage the status bar
    A. Through Uiviewcontroller management (each uiviewcontroller can have its own different status bar) in IOS7, the status bar is managed by the Uiviewcontroller by default, and Uiviewcontroller implements the following methods to light Manage the visibility and style of the status bar
    状态栏的样式   - (UIStatusBarStyle)preferredStatusBarStyle;
    状态栏的可见性  -(BOOL)prefersStatusBarHidden;

    #pragma mark-设置状态栏的样式-(UIStatusBarStyle)preferredStatusBarStyle{  //设置为白色  //return UIStatusBarStyleLightContent;  //默认为黑色 return UIStatusBarStyleDefault;}#pragma mark-设置状态栏是否隐藏(否)-(BOOL)prefersStatusBarHidden{ return NO;}

    B. Through UIApplication management (the status bar of an application is unified by it) if you want to use uiapplication to manage the status bar, first you have to modify the Info.plist settings, add the selected row, and set to No, this article is detailed in the iOS Applicati On to manage battery bar status


    Settings for Info.plist


    Code:

    //通过sharedApplication获取该程序的UIApplication对象UIApplication *app=[UIApplication sharedApplication];//设置状态栏的样式//app.statusBarStyle=UIStatusBarStyleDefault;//默认(黑色)//设置为白色+动画效果[app setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];//设置状态栏是否隐藏app.statusBarHidden=YES;//设置状态栏是否隐藏+动画效果[app setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];

    C. Summary

    If the style of the status bar is set only once, it is managed with uiapplication, and the uiapplication can provide an animated effect;
    If the status bar is hidden, The style is different then use each controller to manage its own status bar.

  • OpenURL: Method
    UIApplication has a very powerful OpenURL: Method
    -(BOOL) OpenURL: (nsurl*) URL;
    OpenURL: Some of the features of the method are

    uiapplication *app = [ uiapplicationsharedapplication]; call [app Openurl:[ "tel://110"], SMS [app Openurl:[ "sms://10086"]; email [app Openurl:[ "mailto://[email protected]"]; open a web resource [app Openurl:[nsurl urlwithstring:@ "HTTP +/" Www.baidu.com "]; open another APP OpenURL method, you can open the other app.              

    System internally based on different headers to make different corresponding 。

  • Judging the running state of a program

      //判断程序运行状态  /*   UIApplicationStateActive,    UIApplicationStateInactive,    UIApplicationStateBackground   */UIApplication *app = [UIApplication sharedApplication];if(app.applicationState ==UIApplicationStateInactive){ NSLog(@"程序在运行状态"); }
  • Prevent the screen from darkening into hibernation
      //阻止屏幕变暗,慎重使用本功能,因为非常耗电。 UIApplication *app = [UIApplication sharedApplication]; app.idleTimerDisabled =YES;
UIApplication Delegate

When the app receives interference, such as a call in the program's operation, it generates some system events, and Uiapplicaiton notifies its proxy delegate object, allowing delegate agents to handle these system events.
The time that delegate can handle includes

1. Application lifecycle events (such as program startup and shutdown)
2. System events (such as incoming calls)
3. Memory warning (more useful)

每当我们创建项目时,程序中的AppDelegate文件就是UIAppliacation的代理,我们可以发现它已经遵守了UIApplicationDelegate。

@interface AppDelegate : UIResponder <UIApplicationDelegate>
Now let's take a look at the Appdelegate method.

Appdelegate: Monitoring the life cycle of an applicationThe following approach is the life cycle approach of the applicationThe Appdelegate method is called when the application starts to complete-(BOOL) Application: (UIApplication *) Application didfinishlaunchingwithoptions: (Nsdictionary *) Launchoptions {NSLog (@ "%s", __func__);ReturnYES;}Called when the application loses focus-(void) Applicationwillresignactive: (UIApplication *) Application {NSLog (@ "%s", __func__);}Called when the application enters the background-(void) Applicationdidenterbackground: (UIApplication *) Application {NSLog (@ "%s", __func__);Save some information}//called when the application enters the foreground-(void) Applicationwillenterforeground: ( Span class= "hljs-built_in" >uiapplication *) application {nslog ( @ "%s", __func__);} //call //can interact with the user only when the application fully acquires focus-(void) applicationdidbecomeactive: (uiapplication *) Application { Span class= "hljs-built_in" >nslog (@ "%s", __func__);} //when the application is closed-(void) Applicationwillterminate: (uiapplication *) application {}//called when a memory warning is received-( void) applicationdidreceivememorywarning: (UIApplication * ) application{}               


Xx_cc
Links: Http://www.jianshu.com/p/f0a2117406d8
Source: Pinterest
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

Ios-uiapplication detailed

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.