0

這是如此基本,希望它會得到迴應。我找不到後來建模的例子。我基本上想要調用視圖時清除/刪除一個NSMutableDictionary。有一個按鈕添加一個整數和一個單獨的按鈕刪除整數。有一個最終按鈕將字典保存到NSUserDefaults並返回到前一個視圖。我是否需要在每個IBAction或viewDidLoad中調用字典來首先創建它並引用它?請指教。使用UIButtons創建/刪除/保存一個NSMutableDictionary到NSUserDefaults

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]; 
} 

回答

0

我看不到陣列的任何初始化。您可以在發送消息之前初始化它。您還必須檢查值是否存在於用戶默認值中。如果存在,你應該使用它,否則創建它。

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

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

除此之外,你可能想呼籲用戶默認synchronize並在dealloc方法釋放exampleDict

+0

如果我在另一個視圖中調用保存的exampleDict,IBAction下面的代碼是否足夠好? NSDictionary * exampleDict = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@「dictionaryKey」]; – StreaminJA 2011-05-26 16:20:03

+0

這應該工作。你是不是'無'? – 2011-05-26 16:22:21

+0

不在家,但我很感激你,如果它。 95%完成。 – StreaminJA 2011-05-26 16:24:18

相關問題