views:

42

answers:

2

Im trying to send a float from one viewcontroller to another.

Ok Ive tried using NSUserDefaults to go about this. First I tested it with a string and it worked, but now I'm struggling to do the same with my float. Any help would be appreciated! :) Heres my code

In my firstviewcontroller.h file i have

IBOutlet UITextField *nameField;
IBOutlet UILabel *greeting;
 float RWI; 
float Liters;

@property(nonatomic) float *Liters;`
@property(nonatomic, retain); IBOutlet UILabel *greeting;
@property(nonatomic, retain) IBOutlet UITextField *nameField;

-(IBAction) updatePrefs:(id) sender; @property(nonatomic) float *RWI; `

In my .m file I have float RWI; //@synthesize RWI; @synthesize Liters; @synthesize nameField,greeting;

-(IBAction) updatePrefs:(id) sender
{   
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:nameField.text forKey:@"greeting"];
[prefs setFloat:20 forKey:@"Liters"];
[prefs synchronize]

Then for the secondviewcontroller.h file

IBOutlet UILabel *greeting;
float *Liters;
}
@property(nonatomic, retain) IBOutlet UILabel *greeting;
@end`

In my .m file

@implementation secondviewcontroller
@synthesize greeting;
@synthesize Liters;

- (void)viewDidLoad {
[super viewDidLoad];NSString *prefs = 
[[NSUserDefaults standardUserDefaults] objectForKey:@"greeting"];
float Liters  = [prefs floatForKey:@"Liters"];
greeting.text = prefs;  
}`

Why does my float give errors? Any help would be appreciated! :)

+3  A: 

The error you are experienced is due to the fact that prefs is NOT [NSUserDefaults standardUserDefaults] as it should be, because in your previous statement you do

NSString *prefs = 
[[NSUserDefaults standardUserDefaults] objectForKey:@"greeting"];

therefore, prefs is a NSString object. You need to modify

float Liters  = [prefs floatForKey:@"Liters"];

to

float Liters  = [[NSUserDefaults standardUserDefaults] floatForKey:@"Liters"];
unforgiven
A: 

You can pass a float variable from one view to another view by implementing getter and setters in the delegate class.

In delegate .h file

Include UIApplication delegate

@interface DevAppDelegate : NSObject <UIApplicationDelegate>

float currentValue;

- (void) setCurrentValue:(float) currentValue;
- (float ) getCurrentValue; 

In Delegate implementation class .m

-(void) setCurrentValue:(float) storydata{
currentValue = storydata;
}

-(float ) getCurrentValue{
return currentValue;
}

So the value you to assess is set in the currentValue by setters method and class where you want the value ,just use the getter method.

All the best

Warrior