Let's say I have:
FirstViewController.h
FirstViewController.m
FirstViewController.xib
SecondViewController.h
SecondViewController.m
SecondViewController.xib
In the FirstViewController.h there is:
#interface FirstViewController : UIViewController
{
int number;
}
#property (nonatomic, retain) int number;
#end
And in FirstViewController.m there is:
- (void)viewDidLoad
{
int number = 4;
}
Is there a way that I could write a function for SecondViewController that could change the value for int number from 4 to let's say 9?
I don't know how to change variables from another XIB or .m file...
First, you probably don't mean to retain an `int.
Second, you do not need to declare int number = 4; but just number = 4;.
Third, if the SecondViewController can access an instance of the FirstViewController *firstViewController, then it can change the value by
[firstViewController setNumber:9];
Depending on your hierarchy, you may be able to access firstViewController through the navController stack, for example.
Related
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.
hey guys i'm making an app that has 2 views. the first view is where the user inputs the numbers and when they hit calculate button.. its takes them to a new view where the answer is displayed on a textfield. the calculation is handled by a different file. "calc.h " and "calc.m"
this is the main view files (the view where the user enters the numbers )
#import <UIKit/UIKit.h>
#interface test2ViewController : UIViewController {
IBOutlet UITextField *num1; //input number 1
IBOutlet UITextField *num2; // input number2
}
#property (nonatomic,retain) UITextField *num1;
#property(nonatomic, retain)UITextField *num2;
-(IBAction)calculate:(id)sender; //the calculate button
-(IBAction)exit:(id)sender;
#end
the answer is displayed in a different view that shows up when the user hits the calculate button. below is the code for that !
#import "test2ViewController.h"
#import "answer.h"
#import "calculate.h"
#implementation test2ViewController
#synthesize num1,num2;
-(IBAction)calculate:(id)sender{
calculate *testclass = [[calculate alloc]init];
answer *view = [[answer alloc]initWithNibName:nil bundle:nil];
[self presentModalViewController:view animated:YES];
int i = [[num1 text] intValue];
testclass.number1 = i;
int j = [[num2 text] intValue];
testclass.number2 = j;
[testclass calc];
}
".h" file of the view that displays the answer
#import <UIKit/UIKit.h>
#interface answer : UIViewController {
IBOutlet UITextField *text;//textfield to display answer
}
#property(nonatomic,retain) UITextField *text;
-(IBAction)back:(id)sender;
#end
".m" file
#import "answer.h"
#import "test2ViewController.h"
#import "calculate.h"
#implementation answer
#synthesize text;
-(IBAction)back:(id)sender{
test2ViewController *view = [[test2ViewController alloc]initWithNibName:nil bundle:nil];
[self presentModalViewController:view animated:YES];
}
the next is an objective c class file that does the calculation. it has one function that does the calculation and here is the ".h" and ".m" file
".h"
#import <Foundation/Foundation.h>
#interface calculate : NSObject {
int number1;
int number2;
NSString *ans;
}
#property int number1;
#property int number2;
#property (nonatomic , retain) NSString *ans;
-(void)calc;
#end
".m"
#import "calculate.h"
#import "answer.h"
#import "test2ViewController.h"
#implementation calculate
#synthesize number1,number2,ans;
-(void)calc{
int i = number1 + number2;
answer *ans1 = [[answer alloc]init];
ans = [NSString stringWithFormat:#"%d",i];
ans1.text.text = ans;
}
#end
so as you can see the above function calculates the answer..puts it into a string and sets that to the textfield. but the textfield doesn't show anything..so the problem here is that i cannot access the textfield even though i created an object from it....
Im a bit confused to what your trying to accomplish, do you want to use an NSString or the text UITextField in another class? If thats the case give the string that is carrying whatever you want to be displayed a #property, then set whatever you want the strings value to it, next import the calc.h (#import "calc.h") in the second class, then in the interface create this calc *getString; create a #property for that, #synthesize it. Then to get the value of the string from calc do something like this getString.SomeStringName, now you are able to do whatever you want with it.
I think this is what you want? if not feel free to comment. Good Day :)
Edit: Im going to give you an example because this is a bit confusing the way i wrote it lol
So here is your calc.h file, also remember im typing this online and not in xcode, so if i spell something wrong or make a simple mistake, thats why:
#interface calc : UIViewController {
NSString *answer;
}
#property (nonatomic, retain) NSString *answer;
#end
Your .h could have more
Now lets hop into your .m
#implementation calc
#synthesize answer;
//do all the work to get the answer, once you have it do this
[answer retain];
//load your new view controller
Lets hop into your other view controller that will be loaded
this is .h file of it
#import "calc.h"
#interface secondController : UIViewController {
calc *getAnswer;
}
#property (nonatomic, retain) calc *getAnswer;
#end
Then go to your .m
#implementation secondController
#synthesize getAnswer;
-(void)viewDidLoad{
WhateverYouWantTheStringToBeSetTo.text = getAnswer.Answer;
}
This should then grab the string from the other controller and allow you to use it in this one..
Hope this helps :)
The problem is that your "ans" UIViewController did not load yet.
The most standard way to do this is to give your UIViewController "ans" a #property with the result. Then in the "ans" viewDidLoad method, set the text field to the appropriate value.
i have got two view.
First: FirstViewController
Second: SecondViewController
FirstViewController is my UINavigationController's root controller and inside FirstViewController I ve got UITableView. When a cell is clicked in UITableView, the view is navigated to SecondViewController. Inside SecondViewController i have UILabel. I want to assign this UILabel's value to the cell which is clicked at FirstViewController when Back button is clicked in Navigation Bar. What am i supposed to do to implement this?
I can pass value to SecondViewController from FirstViewController by creating:
SecondViewController *sv;
sv.somestring = someanotherstring;
but can not implement this at SecondViewController to pass the value to a NSString in FirstViewController.
Can u help me please?
Thank you.
ae
The typical way to handle this in the iPhone SDK is to define a delegate protocol. For instance:
#protocol SecondViewControllerDelegate
- (void) viewControllerWillDisappearWithLabelText: (NSString*)text;
#end
Then you would add a delegate property to your SecondViewController, like:
//in the .h file
#interface SecondViewController : UIViewController {
//declare instance variables
}
#property(nonatomic, assign) id<SecondViewControllerDelegate> delegate;
#end
//in the .m file
#implementation SecondViewController
#synthesize delegate;
//[code...]
#end
Then you would update FirstViewController to implement the delegate protocol:
//in the .h file
#interface FirstViewController : UIViewController<SecondViewControllerDelegate> {
//[instance variables]
}
//[methods and properties]
#end
//in the .m file
#implementation FirstViewController
//[code...]
- (void) viewControllerWillDisappearWithLabelText: (NSString*)text {
//do whatever you need to do with the text
}
//[code...]
#end
...and to set the delegate field when FirstViewController creates the SecondViewController:
SecondViewController* sv = [[SecondViewController alloc] init];
sv.somestring = someanotherstring;
sv.delegate = self;
Finally, in SecondViewController you implement viewWillDisappear to be roughly like:
- (void) viewWillDisappear: (bool)animated {
[super viewWillDisappear:animated];
if (self.delegate) {
[self.delegate viewControllerWillDisappearWithLabelText: myLabel.text];
}
}
Ya , there is much a easy way to handle this.....
You can take a Global Variable
In your Delegate.h file declare your variable:
#interface Smoke_ApplicationAppDelegate : NSObject {
UIWindow *window;
UINavigationController *navigationController;
NSString *messageString; //This would be your String Variable
}
#property(nonatomic,retain)NSString *messageString;
Secondly in Delegate.m file
#implementation Smoke_ApplicationAppDelegate
#synthesize window;
#synthesize navigationController;
#synthesize messageString; // Synthesize it over here..
This is Done .Now you can use this String Variable in All/any class you want..
To use this Global Variable.
Just import you Delegate file make the obj of it....
import "DelegateFile.h"
#implementation About
DelegateFile *appDel;
Now in Your class.m
-(void)viewDidLoad { [super viewDidLoad];
appDel=[[UIApplication sharedApplication]delegate];
}
Now you can access it anywhere in your class by this Object:
appDel.messageString
Just follow my Steps Carefully , I am sure this is definitely going to help you.....
Have a easy life,
Declare a string (stringVal)in the appdeleage and set its propert as nonatomic and retain, synthesize it also.In the second view controller you can set the label value to the appdelegate string([appdelegate setStringVal:label.text];) .You can get this value in the first view controller and use it in table(NSString *localString=appdelegate.stringVal];).
All the best.
I have an iphone application containing two views
The first view have a button, now
i want to show the title of the button on the second view when that button is clicked.
How can i do it because if we save the title into a string ,the string get emptied when second view is loaded ?
In the interface declare the string and make a property:
#interface MyViewController : UIViewController {
NSString *string_i_want_to_set;
}
#property (nonatomic, retain) NSString *string_i_want_to_set;
#end
In the implementation synthesize the string after #implementation MyViewController like this:
#import "MyViewController.h"
#implementation MyViewController
#synthesize string_i_want_to_set;
// OTHER CODE HERE...
#end
Then when you alloc/init the view controller you can set the property like this:
MyViewController *myVC = [[MyViewController alloc] init];
myVC.string_i_want_to_set = #"...."
Hope this gives you more detail.
Thanks
James
you can make object of second view and can pass string to it
view2object.view2string=#"anything" or label.text;
I am very new to objective-c and having a problem to initialize an object in view controller. The problem I am having is that when setTemp method is called, "0" is printed on the screen instead of the value of cTemp I would like it to be. Can anyone help me on this problem?
Below are excerpts of the code I have.
SJT.h
#import <Foundation/Foundation.h>
#import <stdlib.h>
#interface SJT : NSObject {
int cTemp;
}
- (int) newTemp;
#end
SJT.m
#import "SJT.h"
#implementation SJT
- (int) newTemp
{
cTemp = 25 + rand() % 8;
return cTemp;
}
#end
SJTViewController.h
#import <UIKit/UIKit.h>
#class SJT;
#interface SJTViewController : UIViewController {
IBOutlet UILabel *temp;
SJT *sjt;
}
#property (retain, nonatomic) UILabel *temp;
#property (retain, nonatomic) SJT *sjt;
- (IBAction) setTemp: (id) sender;
#end
SJTViewController.m
#import "SJTViewController.h"
#import "SJT.h"
#implementation SJTViewController
#synthesize temp;
#synthesize sjt;
- (IBAction) setTemp: (id) sender
{
NSString *tempText = [[NSString alloc] initWithFormat:#"%d",sjt.newTemp];
temp.text = tempText;
[tempText release];
}
.
.
.
#end
The problem is that you're mistaking property syntax for a method call; i.e.
sjt.newTemp
would become a call to [sjt newTemp]. Which happens to be exactly what you want, except that you have not specified in your header/implementation that there actually is a property called newTemp.
So, in this scenario what you want to do is either a) define the property in the header:
#property(nonatomic, readonly) int newTemp;
or b), just call the method newTemp:
[sjt newTemp]
Are you certain that sjt is not nil? You don't provide the code where and instance of SJT is constructed. In Objective-C you can call a method on a nil reference without error, and if you do so on a method that returns an int it will return 0.
So sjt.newTemp will return 0 if sjt is nil.
Both Jacob and teabot have pointed out valid possible reasons -- which one is correct (or both!) depends on pieces of code we can't see in your post.
Based on what you've written so far, you might not be thinking of newTemp as a property, but more as a function call, so I would suggest changing your code to:
- (IBAction) setTemp: (id) sender {
int tempInt = [self.sjt newTemp];
self.temp.text = [NSString stringWithFormat:#"%d", tempInt];
}
which is functionally equivalent. Note the convenience constructor stringWithFormat: returns an autoreleased object, which is then retained by the retain property text of the temp UILabel.
The other thing to double-check in your code is that self.sjt is not nil, which is exactly what teabot said. Objective-C returns 0 on method calls invoked on a nil pointer.