【问题标题】:Using UIButtons to create/remove/save a NSMutableDictionary to NSUserDefaults使用 UIButtons 创建/删除/保存 NSMutableDictionary 到 NSUserDefaults
【发布时间】:2011-05-23 19:44:20
【问题描述】:

这是非常基本的,希望它会得到回应。我找不到一个可以模仿的例子。我本质上想要一个 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];
}

【问题讨论】:

    标签: objective-c uibutton plist nsuserdefaults nsmutabledictionary


    【解决方案1】:

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

    - (void)viewWillAppear:(BOOL)animated {
        [super viewWillAppear:animated];
    
        exampleDict = [[[NSUserDefaults standardUserDefaults] objectForKey:@"dictionaryKey"] mutableCopy];
        if ( !exampleDict ) {
            exampleDict = [[NSMutableDictionary alloc] init];
        }
    }
    

    除此之外,您可能希望在用户默认值上调用synchronize,并在dealloc 方法中释放exampleDict

    【讨论】:

    • 如果我在另一个视图中调用保存的 exampleDict,下面的代码在 IBAction 下是否足够好? NSDictionary * exampleDict = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"dictionaryKey"];
    • 不在家,但如果在家,我很感激你。 95% 完成。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-29
    • 2016-11-02
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多