To achieve this kinds of scenario, we can use NSUserDefaults. From anywhere in your code, you can set a value for a key :
int userAge = 21; // Just an example
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) {
[standardUserDefaults setObject:[NSNumber numberWithInt:userAge] forKey:@"age"];
[standardUserDefaults synchronize];
}
And get it back from any other place :
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSNumber *age = nil;
if (standardUserDefaults)
age = [standardUserDefaults objectForKey:@"age"];
userAge = [age intValue]
You can also set an initial value :
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *appDefaults = [NSDictionary
dictionaryWithObject:[NSNumber numberWithInt:13] forKey:@"age"];
[defaults registerDefaults:appDefaults];
You can write the value into
NSUserDefault
like the following:[[NSUserDefaults standardUserDefaults] setValue:[myTextField stringValue] forKey:@"Person"];
And read it later like the following:
[myTextField setStringValue:[[NSUserDefaults standardUserDefaults] stringForKey:@"Person"];
Also, if you have complex data, you may want to create a wrapper class with setters and getters.