This question has probably been asked before so I\'m sorry.
I am working on an iPhone app and lets say I have a variable, var, in class1. I want to add a UIButton in cl
The problem with the snippet of code you're showing is that NSUserDefaults only writes the values down to disk when the app quits (or probably also when it's sent to the background in iOS 4). If you need to force NSUserDefaults to write the values of the keys to disk, call the [[NSUserDefaults standardUserDefaults] synchronize] method on it.
Also, instead of using removeObjectForKey: in resetVar, why not using setDouble:forKey: instead? This way you could also get rid of the "double var" ivar in Class1, just using NSUserDefaults as store of the data.
Here's a bit of info about the synchronize method, from the NSUserDefaults documentation:
Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.
This is how I would implement what you described in your code:
@interface Class1
{
}
- (void)resetVar;
@end
@implementation Class1
- (void)viewDidLoad
{
[self resetVar];
}
- (void)resetVar
{
[[NSUserDefaults standardUserDefaults] setDouble:0.0 forKey:@"count"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
@end
@interface Class2
{
Class1 *classObj;
}
- (IBAction)reset:(id)sender;
@end
@implementation Class2
- (void)dealloc
{
[classObj release];
}
- (void)viewDidLoad
{
classObj = [[Class1 alloc] init];
}
- (IBAction)reset:(id)sender
{
[classObj resetVar];
}
@end