使用UIButtons创建/删除/保存NSMutableDictionary到NSUserDefaults

时间:2011-05-23 19:44:20

标签: objective-c uibutton plist nsuserdefaults nsmutabledictionary

这是如此基本,希望它会得到回应。我找不到一个模型的例子。我本质上希望在调用视图时清除/删除NSMutableDictionary。有一个按钮添加一个整数和一个单独的按钮删除整数。有一个最终按钮将字典保存到NSUserDefaults并返回上一个视图。我是否需要在每个IBAction或viewDidLoad中调用字典来首先创建它然后引用它?请指教。

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:exampleDict forKey:@"dictionaryKey"];
[self.parentViewController dismissModalViewControllerAnimated:YES];
}

-(void)viewDidLoad {
}

- (void)dealloc{
[B1 release];
[B2 release];
[Bdone release];
}

1 个答案:

答案 0 :(得分:0)

我没有看到任何数组初始化。您应该先将其初始化,然后再向其发送消息。您还必须检查用户默认值中是否存在该值。如果它存在,你应该使用它,否则创建它。

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    exampleDict = [[[NSUserDefaults standardUserDefaults] objectForKey:@"dictionaryKey"] mutableCopy];
    if ( !exampleDict ) {
        exampleDict = [[NSMutableDictionary alloc] init];
    }
}

除此之外,您可能希望在用户默认设置上调用synchronize,并在exampleDict方法中发布dealloc