Search code examples
iosuilabeluitabbartabbarcontroller

Passing the value of UILabel from FirstView to SecondView on a Tabbar Application


I am trying to make an app which is getting data from a Weather Station. It is a tabbar based application. I have two viewcontrollers: FirstViewController and SecondViewController.

In the FirstViewController I am doing most of the job. Using the values which are coming from xml parsing and assigning these values to UILabels. That is working fine. I am using if() in order to assign UILabel the name of the wind according to its angle like:

In my FirstViewController.m

-(void)setWindDirectionName 
{    
   if(windDirectionAngle >= 0 && windDirectionAngle <=11.25f) labelWindDirectionName.text = @"N";
   if(windDirectionAngle > 11.25f && windDirectionAngle <=33.75f) labelWindDirectionName.text = @"NNE";
   if(windDirectionAngle > 33.75f && windDirectionAngle <= 56.25f) labelWindDirectionName.text = @"NE";
   if(windDirectionAngle > 56.25f && windDirectionAngle <=78.75f) labelWindDirectionName.text = @"ENE";
   if(windDirectionAngle > 78.75f && windDirectionAngle <=101.25f) labelWindDirectionName.text = @"E";
   .
   .
   . so on

In the SecondViewController I have UILabel and want it to take the value of labelWindDirectionName.text from FirstViewController.

my SecondViewController.h

 @interface SecondViewController : UIViewController <CLLocationManagerDelegate>
 {
    NSString *windName;
  }
  @property (strong,nonatomic) NSString *windName;
  @property (strong, nonatomic) IBOutlet UILabel *labelCompassViewWindDirectionName;

  @end

and in SecondViewController.m

 FirstViewController *fvc = [[FirstViewController alloc]init]; 
 windName = fvc.labelWindDirectionName.text;
 labelCompassViewWindDirectionName.text = windName;//getting null probably making completely new  object;

How is it possible to pass data (UILABEL.TEXT) to another view in a tabbar based application? Where am I making mistake? thanks


Solution

  • Here in your code

    FirstViewController *fvc = [[FirstViewController alloc]init]; 
    

    you are allocating new instance of FirstViewController so it will return null. If you need to access those names then you can store then in NSUserDefaults and then can access wherever you need.

    Ex : In FirstViewController : Save name and others as :

        [[NSUserDefaults standardUserDefaults] setObject:labelWindDirectionName.text forKey:@"windName"];//Note : Here windName is a key so you can save diffrent data using diffrent keys and same way can access those data using these keys whereever you require.
        [[NSUserDefaults standardUserDefaults] synchronize];
    

    and for accessing in SecondViewController use this

    labelCompassViewWindDirectionName.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"windName"];
    

    Hope it helps you.