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

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.

Related

How to pass data between not neighbor view controllers in Storyboard

I've stuck in the problem.
I have a storyboard with several view controllers.
What I need to do is:
I need to pass an array from FirstViewController to SecondViewController (they are not neighbors and are not connected via segue) where PikerView will upload the array. After that the picked result should be passed to ThirdViewController.
I have tabbed applicateion where FirstViewController and SecondViewControllers are connected to Tab Bar View Controller and ThirdViewController is connected with SecondViewController via Push Segue.
See how I try to pass data form First to Second
CategoryExpencesViewController.h
#import <UIKit/UIKit.h>
#import "AddCategoryViewController.h"
#import "CategoryPickerViewController.h"
#interface CategoryExpencesViewController : UITableViewController <AddCategoryViewControllerDelegate>
#property(nonatomic, weak) IBOutlet UIBarButtonItem *editButton;
#property(nonatomic, strong) NSMutableArray *categories; //list of category items
#property(nonatomic, strong) NSMutableArray *listOfCategories; //list of category names
CategoryExpencesViewController.m
-(void)updateArray
{
CategoryPickerViewController *controller = [[CategoryPickerViewController alloc]init];
controller.categoryList = [[NSMutableArray alloc]init];
controller.categoryList = listOfCategories;
NSLog(#"%d", [listOfCategories count]);
NSLog(#"%d", [controller.categoryList count]);
}
I think you need this
Use your's Push Segue.
segue.sourceViewController (or self) will point at SecondViewController.
segue.sourceViewController.tabBarController will point at Tab Bar Controller.
From Tab Bar Controller you will find your's FirstViewController.
I suppose you would have solved it, but i post this just for the record:
Wrap the array into a class, and make it have a static construction method:
Wrapper.h:
#property (nonatomic, strong) NSMutableArray* array;
+(Wrapper*)createArray;
Wrapper.m:
+(Wrapper*)createArray{
static Wrapper* instance = nil;
if (instance == nil) {
instance = [[Wrapper alloc] init];
//Your initialization code for the array
}
return instance;
}
Then, in your FirstViewController:
-(void)updateArray{
CategoryPickerViewController *controller = [[CategoryPickerViewController alloc]init];
controller.categoryList = [[NSMutableArray alloc]init];
controller.categoryList = [[Wrapper createArray] array];
NSLog(#"%d", [listOfCategories count]);
NSLog(#"%d", [controller.categoryList count]);
}
As this is the first call to Wrapper, the array is generated.
Then in your SecondViewController, when you call:
secondView.categoryList = [[Wrapper createArray] array];
and you obtain the same array as in FirstViewcontroller.
have you thought of NSUserDefault try it and you can also create a instance global variable in AppDelegate class and access it by creating an instance of AppDelegate in any other ViewController but i think NSUserDefault is the best option from all.

Accessing variable values from one view in another

I'm having some trouble understanding how variable values are passed from one view to another. I have a UITextField in the firstview that the user enters a number into. When the user taps a button, that number is multiplied by 2 and the result is displayed on a UILabel in the second view. This is what I have thus far
FirstViewController.h
#interface FirstViewController : UIViewController{
UITextField *numberTextField;
NSNumber *aNumber;
}
#property (nonatomic, retain) IBOutlet UITextField *numberTextField;
#property (nonatomic) NSNumber *aNumber;
-(IBAction)calculate;
#end
FirstViewController.m
#implementation FirstViewController
#synthesize numberTextField, aNumber;
-(double)doubleNumber{
double number = [numberTextField.text doubleValue] * 2;
return number;
}
-(IBAction)calculate{
self.aNumber = [NSNumber numberWithDouble:[self doubleNumber]];
}
//more default code continues below
SecondViewController.h
#import "FirstViewController.h"
#interface SecondViewController : FirstViewController{
UILabel *numberLabel;
}
#property (nonatomic, retain) IBOutlet UILabel *numberLabel;
#end
SecondViewController.m
#implementation SecondViewController
#synthesize numberLabel;
- (void)viewDidLoad
{
[super viewDidLoad];
numberLabel.text = [NSString stringWithFormat:#"%#",aNumber];
}
Best and Easy Way to store value globally
set you object with your keyword
[[NSUserDefaults standardUserDefaults] setObject:#"Ajay" forKey:#"name"];
than get that object any where in you project
NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:#"name"];
You should accomplish what you want by using a segue. Create a segue in your storyboard and then call it in your firstviewcontroller with - (void)performSegueWithIdentifier:(NSString *)identifier sender:(id)sender. Then to pass data, import your secondviewcontroller.h file with a property for the value you want to pass and setup - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender.
In that method you can pass things by using [segue.destinationViewController ###call the setter for the property in your secondViewController.h file###];
If this isn't clear, or you need more help just let me know.
I'm assuming that the FirstViewController is instantiating the SecondViewController. If that is so, then you just pass aNumber to the SecondViewController using an additional property:
// add an additional property to the SecondViewController
#property (nonatomic, retain) NSNumber *aNumber;
When you instantiate the SecondViewController inside the FirstViewController, you just pass that value to the SecondViewController before you load it:
// inside FirstViewController
SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:#"SecondViewController" bundle:nil];
secondViewController.aNumber = aNumber;
// inside SecondViewController
- (void)viewDidLoad
{
[super viewDidLoad];
numberLabel.text = self.aNumber;
}
Mmm... Pay attention to not confuse views and viewControllers!!!
A viewController can manage more than a view. For example in your code you have a UITextField, a UILabel and probably a UIButton. These are all views that are managed by two viewsController (FirstViewController and SecondViewController).
As long as you have so few views to work with you can use just one viewController and pass the value you want to your UILabel directly:
- (void)calculateAndPassValue
{
aNumber = [NSNumber numberWithDouble:[self doubleNumber]];
numberLabel.text = [NSString stringWithFormat:#"%#",aNumber];
}
Otherwise, if your goal is passing variable values from one viewController to another. Well... There are many ways you can obtain that, for example:
Creating an ivar.
Using a singleton.
Saving your data in NSUserDefault.
Creating a database on disk.
First and second cases are good if you need to manage your data while your app is running. Third and fourth if you want to memorize your data for future use and retrieve them at next start up.
Try to search keys like ivar, singleton, NSUserDefault and you'll find many discussions and lines of sample code.

iPhone SDK, passing strings through views

I'm trying to pass a string through two views on an iPhone app. On my second view that I want to recover the string in the .h i have:
#import <UIKit/UIKit.h>
#import "MBProgressHUD.h"
#import "RootViewController.h"
#interface PromotionViewController : UITableViewController {
NSString *currentCat;
}
#property (nonatomic, retain) NSString *currentCat;
#end
And in the .m i have:
#synthesize currentCat;
However, in the first view controller when I try and set that variable I get a not found error:
PromotionViewController *loadXML = [[PromotionViewController alloc] initWithNibName:#"PromotionViewController" bundle:nil];
[self.navigationController pushViewController:loadXML animated:YES];
[PromotionViewController currentCat: #"Test"];
That third line gives me a: Class method +currentCat not found
What am i doing wrong?
Tom,
The issue in your code appears that you are trying to set the string using a static method call to the class. This would work if you implemented a static method named currentCat:
I don't think this is what your want.
See below on how to correct your issue.
[PromotionViewController currentCat:#"Test"];
//This will not work as it is calling the class itself not an instance of it.
[loadXml setCurrentCat:#"Test"];
//This will work. Keep in mind if you are going to call the objective-c
//synthesize setting directly you will need to capitalize the first letter
//of your instance variable name and add "set" to the front as I've done.
//Alternatively in objective-c 2.0 you can also use
//the setter method with the . notation
loadXml.currentCat = #"Test";
//This will work too
You need to get the string like this, as it's a property and not a method:
NSString* myString = controller.currentCat; // where controller is an instance of PromotionViewController
You need to do:
loadXML.currentCat = #"Test";
PromotionViewController *loadXML = [[PromotionViewController alloc] initWithNibName:#"PromotionViewController" bundle:nil];
[loadXML setCurrentCat: #"Test"];
[self.navigationController pushViewController:loadXML animated:YES];
That should do it.

Accessing NSMutableArray in an object from different object

How can I get access to a NSMutableArray that has been hydrated in different Class?
There is my sample code:
Class1.h : I have an iVar NSMutableArray *anArray;
And I #synthesize anArray; it in Class1.m
In the RootViewController I import the Class1.h and addd #Class "Class1";
The in the interface I add the Class1 *aClass1; in the RootViewController.m I #synthesize it and in the ViewWillAppear
aClass1 = [[Class1 alloc] init];
aClass1.anArray = [[NSMutableArray alloc] initWithObjects: #"string1",#"string2",nil];
NSLog(#"aClass1.anArray is Class1 %#",aClass1.anArray); // It works as I expected
Now in the new class I call it DetailsViewController
Same as the RootViewController.h I imported the .h and #class "Class1";.
Also in the DetailsViewController.m I have imported the "Class1.h"
So now in the DetailsViewController I try to do this in the viewWillAppear
NSLog(#"aClass1.anArray in DetailsViewController %#",aClass1.anArray); // PROBLEM: It comes back as null
I have added this sample project in this address: http://www.epicdesign.com.au/test2.zip
You just forgot to set the aClass1 ivar of the details view controller before you pushed it onto the navigation controller. Here is the code that should be in your didSelectRowAtIndexPath method:
DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:#"DetailViewController" bundle:nil];
// ...
// Pass the selected object to the new view controller.
detailViewController.aClass1 = aClass1; // this line was added
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
Once you add the line that I added above, your array will now show up correctly in the detail view controller.
You're accessing a property that you haven't declared yet in the Class1.h, so you must add there:
#property (nonatomic, copy) NSMutableArray *anArray;
Since it should work, I prefer not to pass any NSMutableArray as parameter. You should better declare a NSArray property in Class1.h to pass it to your methods and then mutableCopy it where you want to make modifications to the array (only inside the methods). And remember that mutableCopy and copy increase the retain count of your array, so you must release it when you are done.

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.