Search code examples
objective-ccocoa-touchxcode4.3

Is there a way to make a global label


I want to change the text of a label from another controller you know like defining a global variable.


Solution

  • With the introduction of Automatic Reference Counting with iOS 5, which forces certain programming rules and restrictions, certain programming constructs and accepted practices are no longer possible. The use of the extern is one of the C based directives that is frowned on by the linker. Actually you will get linkage errors if you try to use with ARC enabled.

    However, it is still very possible to use global variables with iOS 5, you just can use the #define directive to do so.

    The following steps demonstrate one possible solution for using global variables.


    1) Declaring a Global Variable :

        NSString * gvar;
        @interface AppDelegate : UIResponder <UIApplicationDelegate>
    

    2) Initializing the Global Variable :

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        // Override point for customization after application launch.
         gvar = [[NSString alloc] initWithString:@"Name1"];
        return YES;
    }
    

    3) Import this AppDelegate file in both your ViewControllers.


    4) Assigning gvar to UILabel in your first ViewController :

    - (void)viewWillAppear:(BOOL)animated
    {
        [super viewWillAppear:animated];
         self.label.text= gvar;
    }
    

    5) Change its value from your second ViewController :

    gvar = [self.songArray objectAtIndex:indexPath.row];
    

    Once you go back to the previous viewController, your label will dispaly the new text.