Using UIButtons to create/remove/save a NSMutableDictionary to NSUserDefaults
This is so basic that hopefully it will get a response. I could not find an example to model after. I essentially want to have a NSMutableDictionary that is cleared/deleted when the view is called. Have a button add an integer and a separate button remove the integer. There is a final button to save the dictionary to NSUserDefaults and return to the previous view. Do I need to call on the dictionary in each IBAction or in the viewDidLoad to first create it and then reference it? Please advise.
example.h
@interface example : UIViewController {
NSMutableDictionary *exampleDict;
UIButton *B1;
UIButton *B2;
UIButton *Bdone
}
-(IBAction)button1;
-(IBAction)button2;
-(IBAction)done;
@property (retain,nonatomic) IBOutlet UIButton *B1;
@property (retain,nonatomic) IBOutlet UIButton *B2;
@property (retain,nonatomic) IBOutlet UIButton *Bdone;
@property (retain,nonatomic) NSMutableDictionary *exampleDict;
@end
example.m
@implementation example
@synthesize exampleDict;
@synthesize B1;
@synthesize B2;
@synthesize Bdone;
@end
-(IBAction)button1{
[exampleDict setValue:[NSNumber numberWithInt:1] forKey:@"one"];
}
-(IBAction)button2 {
[exampleDict removeObjectforKey: @"one"];
}
-(IBAction)done {
[[NSUserDefaults standardUserDefaults] setObject:ex开发者_C百科ampleDict forKey:@"dictionaryKey"];
[self.parentViewController dismissModalViewControllerAnimated:YES];
}
-(void)viewDidLoad {
}
- (void)dealloc{
[B1 release];
[B2 release];
[Bdone release];
}
I don't see any initialization of the array. You should initialize it before you can message to it. You will also have to check if the value exists in the user defaults. If it exists, you should use it otherwise create it.
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
exampleDict = [[[NSUserDefaults standardUserDefaults] objectForKey:@"dictionaryKey"] mutableCopy];
if ( !exampleDict ) {
exampleDict = [[NSMutableDictionary alloc] init];
}
}
In addition to this, you might want to call synchronize
on the user defaults and release exampleDict
in the dealloc
method.
精彩评论