2012-09-15 53 views

回答

4

在iOS上,您可以使用NSUserDefaults在運行之間存儲變量。 請參見下面的示例代碼:

#define HSMEMORY @"hsMemory" // used to prevent errors in writing it repeatedly 

    // Store initial default values. Do this at the beginning of the App like in AppDelegate before the values are used and accessed. 
    // This will set the initial value when the App is first run and nothing has been stored in previous runs. 
     NSNumber *defaultMemory = [NSNumber numberWithDouble:0.0]; 
     NSDictionary *appDefaults = [NSDictionary 
             dictionaryWithObjectsAndKeys: 
             defaultMemory, HSMEMORY, nil]; 
     [[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults]; 

要訪問的變量使用:當你說一個 '變量' 你

[[NSUserDefaults standardUserDefaults] setObject:memory forKey:HSMEMORY]; 
0

我相信:

NSNumber *memory = [[NSUserDefaults standardUserDefaults] objectForKey:HSMEMORY]; 

要重置變量使用意思是一個NSString,所以在這種情況下,你可以使用NSUserDefaults來實現這一點。但請記住,NSUserDefaults,正如名稱所示,應該存儲少量數據,所以不要太多地使用它。

要保存的NSString:

//Initialize NSUserDefaults 
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 
//Store the desired value 
[defaults setObject:@"TEXT TO SAVE OR NSSTRING" forKey:@"CHOOSE A KEY-NAME"]; 
//To retrieve the text when the app launch 
NSString *value_retrieved = [defaults [email protected]"YOUR KEY-NAME"]; 

要保存BOOL關鍵

//Initialize NSUserDefaults 
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 
//Save the Boolean 
[defaults setBool:YES OR NO forKey:@"CHOOSE A KEY-NAME"]; 
//Retrieve the Boolean 
[defaults boolForKey:@"YOUR KEY-NAME"]; 
相關問題