Melbourne
Melbourne

Reputation: 541

How to pass label value in iphone

I have two controllers A & B In B there are one label and one string In A i have write the below code

B *ObjB =[[B alloc]initWithNibName:@"B" bundle:nil];
ObjB.Mylabel.text=[NSString stringWithString:@"Add New name"];
ObjB.MyString=[NSString stringWithString:@"new string name"];
[self.navigationController pushViewController:ObjB animated:YES];
[ObjB release]; 

I am only getting the ObjB.MyString value in B , not getting the label text.Can any one help.Thanks in advance.

Upvotes: 0

Views: 116

Answers (3)

footyapps27
footyapps27

Reputation: 4042

The best way to pass data between two view controllers is to declare a variable in controller B, to hold the labels text. In viewController B's header file

    NSString *labelText;

//Declare its property and synthesize in .m

In controller A, before navigating to controller B, initialize this variable to the text you want, i.e. in this case "Add New Name".

B *ObjB =[[B alloc]initWithNibName:@"B" bundle:nil];
ObjB.labelText = [NSString stringWithString:@"Add New name"];
ObjB.MyString = [NSString stringWithString:@"new string name"];
[self.navigationController pushViewController:ObjB animated:YES];

Next in the viewDidLoad of controller B, assign the label's text to the variable which contains the string.

ViewDidLoad of B
MyLabel.Text = labelText;
//Assuming you have mapped MyLabel to the IB. 

Also i use ARC for all my projects, so I dont use the release command.

Upvotes: 1

Melbourne
Melbourne

Reputation: 541

This solved my problem

B *ObjB =[[B alloc]initWithNibName:@"B" bundle:nil];
[self.navigationController pushViewController:ObjB animated:YES];
ObjB.Mylabel.text=[NSString stringWithString:@"Add New name"];
ObjB.MyString=[NSString stringWithString:@"new string name"];
[ObjB release]; 

Thanks for your immediate response

Upvotes: 0

Alladinian
Alladinian

Reputation: 35616

Well assuming that MyLabel is a UILabel (sidenote: avoid capitalized names for ivars - in Objc capitalized names are used [by convention] for Classes), the reason that the value is not set is because the view hierarchy of your B controller has not yet been loaded (ie your label is nil at this point). So you got three options:

  1. Force the view hierarchy to load & then set your label:

    [ObjB loadView]; // Note: Apple says that you never should call this directly (just to illustrate my point)!!

  2. Let the system load the hierarchy for you by requesting the view first:

    id view = ObjB.view; // This is a bit of a 'hack' actually

  3. Just add another property in your B controller, set that and on viewDidLoad set your label's text (This is the best option in my opinion)

Upvotes: 1

Related Questions