Declaration and use of iOS global variables

Source: Internet
Author: User

In a project, we may need to define several global variables that can be accessed anywhere in our program to improve our development efficiency. How do we implement it in iOS? We mainly use the Appdelegate class to implement. As follows:

(1) AppDelegate.h:

    1. #import <UIKit/UIKit.h>
    2. @interface Appdelegate:uiresponder <UIApplicationDelegate>
    3. @property (Strong, nonatomic) UIWindow *window;
    4. @property (Strong,nonatomic) nsstring *myname; declares a global variable;
    5. @end

(2) VIEWCONTROLLER.M

This is the first page.

  1. #import "ViewController.h"
  2. #import "AppDelegate.h"//need to introduce this header file;
  3. @interface Viewcontroller ()
  4. @end
  5. @implementation Viewcontroller
  6. -(void) Viewdidload {
  7. [Super Viewdidload];
  8. }
  9. -(void) Viewdidappear: (BOOL) animated{
  10. [Super Viewdidappear:true];
  11. appdelegate *app = [[uiapplication Sharedapplication] delegate];
  12. NSLog (@ "%@", App. myName);
  13. App. myName = @ "First page";
  14. }
  15. @end


(3) SECONDVIEWCONTROLLER.M

This is the second page.

  1. #import "SecondViewController.h"
  2. #import "AppDelegate.h"
  3. @interface Secondviewcontroller ()
  4. @end
  5. @implementation Secondviewcontroller
  6. -(void) Viewdidload {
  7. [Super Viewdidload];
  8. }
  9. -(void) Viewdidappear: (BOOL) animated{
  10. appdelegate *app = [[uiapplication Sharedapplication] delegate];
  11. NSLog (@ "%@", App. myName);
  12. App. myName = @ "second page";
  13. }
  14. @end


Finally jump between two pages, the output is as follows:

This means we are working on the same variable. Why is it possible to declare global variables in appdelegate? Because a singleton is used, Appdelegate is a singleton class that implements the Uiapplicationdelegate delegate. As long as we declare the Appdelegate object anywhere in the program, this object is unique, so we can implement the global variable

Declaration and use of iOS global variables

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.