Accessing variables from other viewcontroller [duplicate] - iphone

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Interact with a view controller from another view controller
viewcontrollerOne.h
UILabel *label;
viewcontrollerTwo.m
-(void)myMethod
{
viewControllerOne *obj = [[viewControllerOne alloc]init];
obj.label.text = #"abcd";
}
I want to access variables of one viewcontroller in other view controller.I tried the above method but it's not working for me.i searched other threads but most of the answers told me to declare them in appdelegate. so is there any other way instead of declaring it in appdelegate?

create a new method in viewcontrollerTwo (don't forget to declare it in *.h file):
-(id) setParams:(UILabel *)lb{
labelOne = [[UILabel alloc] init];
labelOne = lb
return self;
}
Then, when you need to puth this view controller from first one:
viewcontrollerTwo *controllerNew = [[viewcontrollerTwo alloc] initWithNibName:#"viewcontrollerTwo" bundle:nil];
[self.navigationController pushViewController:controllerNew animated:YES];
controllerNew = [controllerNew setParams:labelOne];
[controllerNew release];

You code is wrong, you should have labelOne, not label:
obj.labelOne.text = #"abcd";
Also, your label may not exist yet - do you create it in the init function? If you have a xib file for that controller then you need to load that so that all the controls are created and linked up:
viewcontrollerOne *controllerNew = [[viewcontrollerOne alloc] initWithNibName:#"viewcontrollerOne" bundle:nil];
Also, it would be much nicer to declare your label as a property rather than a member variable:
#property (strong, nonatomic) UILabel *labelOne
Then synthesize the setter/getter methods in the implementation file:
#synthesize labelOne;
Finally, Cocoa naming standards are that class names should start with a capital letter.

See its very easy... you can do it through App Delegate class.
Write the Variables which you want in appDelegate class like in .h
UILabel *myLabel;
#property (nonatomic) UILabel *myLabel;
IN .m File :-
synthsize myLabel;
myLabel = [[UILabel alloc]init];
Now in Whichever viewController u need to get this Label do this way :-
in .h file :-
#class AppDelegateClass; //forward decleration
AppDelegateClass *appDelegate;
UILabel *localLabel; //CurrentViewController Label
//Make Property
in .m File :-
//synthesize the Label
appDelegate = (AppDelegateClass *)[[UIApplication SharedApplication]delegate];
//now to acccess it
localLabel = appDelegate.myLabel;
and Finished...
Hope it helps and if then Please Tick as Correct Answer and UpVote the Answer.... :)

Please try below code instead of your code. and it will work fine...
viewControllerOne *obj = [viewControllerOne alloc];
obj.variableName = #"abcd";
[obj initWithNibName:#"nibName"];
Thanks

Related

How Can I Access my ViewController's Property Variables From Another Class?

Ok, this is really bugging me and I am sure the solution is simple... I am unable to set my ViewController's property variables from another class (SeverConnect.m), which I have declared and synthesized properly in my ViewController's .h/.m files:
ServerConnect.h:
#import <Foundation/Foundation.h>
#import "ViewController.h"
#import "Contact.h"
#class ViewController;
#interface ServerConnect : NSObject
{
Contact *newContact;
NSString *codeRawContent;
NSMutableArray *contactListCopy;
... //Other variables declared here, but not shown in order to save space
Inside ServerConnect.m:
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
NSLog(#"parserDidFinish");
newContact = [[Contact alloc] initWithCodeInfo:(NSString *)codeInfo
contactName:(NSString *)completeName
contactImage:(UIImage *)profileImage
contactWebSite:(NSString *)codeRawContent];
[contactListCopy insertObject:newContact atIndex:0];
[ViewController setContactList:contactListCopy]; //Automatic Reference Counting Error Occurs Here: "No known class method for selector 'setContactList:'"
}
As I mentioned above, I have declared and synthesized the property variable, "contactList", in my ViewController's .h/.m files (with no errors):
#property (nonatomic, retain) NSMutableArray *contactList; //In ViewController's .h file
#synthesize contactList; //In ViewController's .m file
Can someone tell me what I am doing wrong? Thanks in advance for any help you can provide!
you are trying to access an instance property on a class:
[ViewController setContactList:contactListCopy];
you need to first create an instance of the ViewController class, and then set its property. Something like this:
ViewController *viewController = [[ViewController alloc] init];
[viewController setContactList:contactListCopy];
In this line of code:
[ViewController setContactList:contactListCopy];
you should be using a variable of type ViewController. The way you are using it, it should be a class method, not a property.
Write something like:
ViewController *viewController = [[ViewController alloc] init];
[viewController setContactList:contactListCopy];

How to pass variable from one controller to another in ios?

I have one controller with variable like
NSString *str;
In same controller i am assigning userId in string str.
I need above userId in another controller to show user data.
How should I get value of userId in another controller?
Below is my code:
MainViewController.h
#property (nonatomatic) NSString *str;
MainViewController.m
#synthesize str;
str = 1;
Now in FirstViewController.h
#property(nonatomatic, retain) MainViewController *mainCon;
FirstViewController.m
#synthesize mainCon;
NSLog(#"user id is %#", mainCon.str);
Here in log i am getting null value.
Your best bet is going to be in the [prepareForSegue] method
within that method I usually have something like
if ([segue.identifier isEqualToString#"segueName"]){
//I use this if statement to check which segue I am performing, if I have multiple
//segues from a single view controller
FirstVc *newViewController = segue.destinationViewController;
newViewController.str = self.str;
}
This will pass the string from your main VC to your new VC. This is all assuming that your transitions are laid out in Interface Builder or some way that gives you access to the segues and identifiers
Take a Property in MainVC and Pass value from FirstVC then It will work for you.
the following code must be in MainVC
#property (strong, nonatomic) NSString *str;
#synthesize str;
in FirstVC
MainVC * vc = [[MainVC alloc]init];
vc.str = #"test";
Step1:
You have to create a viewcontroller class as Constants
Step 2:
You can delete .m file in Constanst class
Step3:
You have to import the Constants.h in Projectname_Prefix.pch which will be xcode's in other resources folder. Now Constant class will act as global class.
Step4:
Now, you can declare variables in Constants.h. The variables those declared in Constants.h will act as global variable. you can access it anywhere.
SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:#"SecondViewController" bundle:nil];
secondViewController.str1 = str;
[self.navigationController pushViewController:secondViewController animated:YES];
It's a quicker and easy solution.

Discrepancy in passing data between classes

Part 1 of the code works fine. Part 2 shows minor changes in the code which causes the code to stop working (without errors/warnings) as expected.
Part 1: (Works)
#import "ClassA.h"
#import "ClassB.h"
#implementation ClassA
- (void) sendData
{
NSString *temp = [NSString stringWithFormat:#"HI!"];
ClassB *classBObject = [[ClassB alloc] init];
classBObject.dataToDisplay = temp;
self.view = classBObject.view;
}
#end
Interface of ClassB:
#import <UIKit/UIKit.h>
#interface ClassB : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *textLabel;
#property NSString * dataToDisplay;
#end
Implementation of ClassB:
#import "ClassB.h"
#implementation ClassB
#synthesize dataToDisplay, textLabel;
- (void)viewDidLoad
{
[super viewDidLoad];
textLabel.text = dataToDisplay;
}
#end
Part 2:
But if I change - (void)sendData of ClassA to the following:
- (void) sendData
{
NSString *temp = [NSString stringWithFormat:#"HI!"];
ClassB *classBObject = [[ClassB alloc] init];
classBObject.textLabel.text = temp; // statement changed from Part 1.
self.view = classBObject.view;
}
and remove textLabel.text = dataToDisplay; from implementation of ClassB, the textLabel on view controller of ClassB does not get updated. Can you please suggest, why is it so?
Thanks!
Edit 1:
In the statement: classBObject.textLabel.text = temp; // statement changed from Part 1., I had missed .text while copy pasting. Please excuse me for that.
The reason that the second technique is incorrect (besides the missing .text at the end of textLabel) is that when you return from the class B initializer, the underlying UILabel corresponding to textLabel undoubtedly has not been created yet. If you look at this diagram you'll see that the view configuration is not completed at the end of the the initialization methods, but rather upon access. So you must defer any access of the user interface controls until viewDidLoad.
Update:
When I run the following code, I get "0x0" in my log, proving that the UILabel on my second view is still nil and has not been initialized yet, as I would have expected. When the viewDidLoad in my second controller sets self.textLabel.text = self.dataToDisplay in viewDidLoad, it works like a champ (as it does for you). But the UILabel IBOutlet property is just not reliable until viewDidLoad.
SecondViewController *controller = [[SecondViewController alloc] init];
NSLog(#"%p", controller.textLabel);
controller.dataToDisplay = #"from first view";
[self presentViewController:controller animated:YES completion:nil];
You are setting a UITextLabel to NSString. Try
classBObject.textLabel.text = temp;
Change this line...
classBObject.textLabel = temp; // statement changed from Part 1.
to
classBObject.textLabel.text = temp; // statement changed from Part 1.
Also, you should do
[self.view addSubView:classBObject.view]; //using navigation controller or presenting modal viewcontroller would be recommended.
instead of
self.view = classBObject.view;
after this line, update the label's text with your value.
classBObject.textLabel.text = temp; // statement changed from Part 1.
I noticed that you're using a weak reference to the UILabel in your classB interface. Any reason you're not using a strong reference? The only time you want to use weak references is to avoid retain cycles. Most likely, your UILabel isn't being retained.
Where do you initialize your UILabel?

Pass variable to another view

I'm trying to set a variable in another view.
I'm in a view which I have named ProgramViewController and from here I would like to set a variable named bands in MyViewController.
I thought it would be as simple as
MyViewController *myViewController = [[MyViewController alloc] init];
myViewController.bands = #"hello world";
[myViewController release];
And in the header of MyViewController:
#interface MyViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> {
NSString *bands;
}
#property (nonatomic, retain) NSString *bands;
That does not work, though.
Can anyone please tell me what I am doing wrong?
EDIT:
I synthesize bands in MyViewController:
#synthesize pageNumberLabel, tableProgram, bands;
But when trying to print it with NSLog in the viewDidLoad of MyViewController I get (null)
NSLog(#"%#", bands);
You need to synthesize the bands variable in MyViewController.m
#synthesize bands;
A variable needs to be synthesize in order to use it as a public property outsize of a class in Objective-C
I solved this in another way. I managed to load the data in MyViewController instead. I was dealing with a page controller and had to populate a UITableView but had troubles loading the data.
This is solved in a completely other way now.

How can I update my view controller's UILabel through another class?

I'm my class i've added a an instance of my view controller, created a property and then synthesized it in my implementation file. I am trying to update the UIlabel in the view controller like this,
NSString *currentChar = [[NSString alloc] initWithFormat:#"%c", ch];
viewController.outputLabel.text = currentChar;
[currentChar release];
My problem is that everything builds without any errors or warnings but the label just doesn't get updated, what am I doing wrong. I'd really appreciate some help on this one.
Are you sure you're referencing the existing viewController and you didn't instantiate a new one? Your property is not declared as copy, correct?
textProcessor.h / .m
#interface textProcessor : NSObject {
MainViewController *mainView;
}
#property (retain) MainViewController *mainView;
#end
#implementation textProcessor;
#synthesize mainView;
MainViewController.h / .m
#interface MainViewController : UIViewController {
UILabel *myLabel;
}
#property (retain) UILabel myLabel;
#end
#implementation MainViewController
#synthesize myLabel;
When you are initializing your textProcessor class, and you set the value for "mainView" like
-(void)viewDidLoad {
[super viewDidLoad];
textProcessor *proc = [[textProcessor alloc] init];
proc.mainView = self;
//note that you are not doing this:
//MainViewController *mainView = [[MainViewController alloc] init];
//proc.mainView = mainView;
//that was creating a new instance variable instead of using self, the existing one
[textProcessor release];
}
Have you created your label in IB? If you are using IB you have to create an IBOutlet for your UILabel. You then make a connection between the UILabel in IB to your IBOutlet in your class.
Have you tried calling the setNeedsDisplay method on the view? Also you may want to try using the setText method instead of assigning directly to the property.