NSUserDefaults for loop for switchCollection - nsuserdefaults

I've make a mySwitchCollection and I need to retrieve the boolForKey value from it to set on or off the switch on my view.
This is the code but I've problem for the [defs boolForKey:arrayCostanti[i]];
arrayCostanti is a static NSString *arrayCostanti[] = {k3D,kAnimazione};
How I can push my arrayCostanti[i] value to boolForKey?
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
//Leggo dal defs gli stati di ogni switch e gli setto lo stato
//NSUserDefaults
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
//mySwitch1.on = [defs boolForKey: k3D];
//ciclo for per settare tutti gli stati degli switch che ho raccolto nel mySwitchCollection
for (int i = 0; i <= 45; i++){
mySwitchCollection[i].on = [defs boolForKey:arrayCostanti[i]];
}
}

You will need to make sure you are storing it correctly as well.
I'm going to assume 'k3D' is a defined NSString for your key.
// saving
mySwitch1.on = YES;
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:mySwitch1.on] forKey:k3D];
// retrieving
BOOL switchOn = [[NSUserDefaults standardUserDefaults] boolForKey:k3D];
The big thing to remember is that NSUserDefaults can only store the main object types, and BOOL is not one of them. So make sure you set your BOOL to an NSNumber first, and you should be good to go.

Related

Outrageous scores values

please can someone help me out here. I am trying to display highscores and scores on my game over screen using the code below but I get these values
High: 327178665342
Score: 89254400
which are not consistent with what the actual scores I have on the hud display.
This is the code I am using to retrieve and display the scores:
-(id)init{
self = [super init];
if (self != nil) {
int score;
_score = score;
self.scoreLabel.string = [NSString stringWithFormat:#"Score: %d",_score];
// 6
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger highScore = [defaults integerForKey:#"BatHighScore"];
// 7
if(score >= highScore) {
highScore = score;
[defaults setInteger:score forKey:#"BatHighScore"];
[defaults synchronize];
}
self.highScoreLabel.string = [NSString stringWithFormat:#"High: %d",highScore]
}
return self;
}
#end
Is there something I am doing wrong here?
It is likely that you never initialize score in your code and get garbage value.
int score; // garbage
_score = score;
Try initializing score with default value you should get better results.
It's not really clear what you are trying to accomplish here, maybe you want to define an designated initializer like that :
-(id)initWithScore:(NSInteger)score {
self = [super init];
if (self != nil) {
_score = score;
// ...

NSMutableArray in NSUserDefaults

I'm sorry for my bad english but i'm trying to explain with best words.
I have some problem when i'm trying to insert an NSMutableArray in NSUserDefaults ([NSUserDefaults setObject:forKey:]: Attempt to insert non-property value ')
My code to insert the array is as follows:
-(void)saveToUserDefaults:(NSMutableArray*)myArray
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSArray *array = [[NSArray alloc ] initWithArray:myArray];
if (standardUserDefaults)
{
[standardUserDefaults setObject:array forKey:#"MyArray"];
[standardUserDefaults synchronize];
}
}
My code to retrieve the array:
-(NSMutableArray*)retrieveFromUserDefaults
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *val = [[NSMutableArray alloc]init];
if (standardUserDefaults)
val = [NSMutableArray arrayWithArray:[standardUserDefaults arrayForKey:#"MyArray"]];
return val;
}
and in my code :
NSMutableArray :
series = [[NSMutableArray alloc]initWithObjects:nil];
//add some object inf my array...
Save my NSMutableArray :
[self saveToUserDefaults:series];
Retrieve my NSMutableArray :
series = [self retrieveFromUserDefaults];
I think it's not the best way to do this, so if anyone have ideas , it'll be helpful for me.
Thanks for reading.
Tommy
Only immutable NSArrays can be placed into defaults. Rather than placing a NSMutableArray there, convert to regular array using [NSArray arrayWithArray:] and place that one into defaults.
For retrieval, retrieve an NSArray and then use [NSMutableArray arrayWithArray:].
You can use following method to get the mutable object from immutable. It's not optimized and only implemented for NSArray and NSDictionary.
+ (id) GetMutable:(id)input {
id result;
if ([input superclass] == [NSArray class] || [input superclass] == [NSMutableArray class]) {
result = [[NSMutableArray alloc] initWithArray:input copyItems:YES];
for (int i = 0; i < [(NSMutableArray*)result count]; i++) {
[(NSMutableArray*)result replaceObjectAtIndex:i withObject:[Globals GetMutable:[(NSMutableArray*)result objectAtIndex:i]]];
}
} else if ([input superclass] == [NSDictionary class] || [input superclass] == [NSMutableDictionary class]) {
result = [[NSMutableDictionary alloc] initWithDictionary:input copyItems:YES];
NSArray *keys=[(NSMutableDictionary*)result allKeys];
for (int i = 0; i < keys.count; i++) {
[(NSMutableDictionary*)result setObject:[Globals GetMutable:[(NSMutableDictionary*)result objectForKey:[keys objectAtIndex:i]]] forKey:[keys objectAtIndex:i]];
}
}
else {
return input;
}
return result;
}
I hope this tutorial helps, who expect answer for this question.
-(void)saveToUserDefaults:(NSString*)myServerName uname:(NSString*)myUserName
pass:(NSString*)myPassword
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) {
[standardUserDefaults setObject:myServerName forKey:#"ServerKey"];
[standardUserDefaults setObject:myUserName forKey:#"UserNameKey"];
[standardUserDefaults setObject:myPassword forKey:#"PasswordKey"];
[standardUserDefaults synchronize];
}
}
-(NSArray*)retrieveFromUserDefaults
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *serverName = nil;
NSString *userName = nil;
NSString *password = nil;
if (standardUserDefaults)
serverName = [standardUserDefaults objectForKey:#"ServerKey"];
userName = [standardUserDefaults objectForKey:#"UserNameKey"];
password = [standardUserDefaults objectForKey:#"PasswordKey"];
NSArray* credentials = [NSArray arrayWithObjects:serverName,userName,password, nil];
return credentials;
}
To Pass values
[self saveToUserDefaults:serverVariable uname:usernameVariable pass:passVariable];
To get Values
NSArray *result=[self retrieveFromUserDefaults];
Happy coding!!!
The contents of your array can only by plist valid objects: (NSString, NSNumber, NSDate, NSData, NSArray, or NSDictionary objects).
See documentation for NSUserDefaults setObject:forKey: and What is a Property List?
Your code needs a lot of clean up. Here is the simple and correct way to access standard user defaults:
The value you pass to your save method does not need to be mutable, although it can be. But since you are not mutating it inside your method, there's no need for it to be mutable. It just has to be not nil, which you'll check before saving:
-(void)saveToUserDefaults:(NSArray*)myArray
{
if (myArray) {
NSUserDefaults *myDefaults = [NSUserDefaults standardUserDefaults];
myDefaults[#"myArray"] = myArray;
}
}
Standard user defaults only returns non-mutable objects, which you can convert to a mutable copy using the "mutableCopy" method:
-(NSMutableArray*)retrieveFromUserDefaults
{
NSUserDefaults *myDefaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *val = [[NSMutableArray alloc] init];
val = [myDefaults[#"MyArray"] mutableCopy];
return val;
}

Can't read NSUserDefaults data between views

Disclaimer: major noob
I'm writing an arithmetic flash card app as a learning project. I have a UITabViewController with the bottom tab bar that toggles between a few different views. Everything works okay until I try to set NSUserDefault boolean values in the Settings view controller and try to read those values in the Flashcards view controller.
The settings view has a switch to enable/disable each operator (addition, subtraction, etc) and the flashcard view should randomly present a flash card if that type of operation was enabled.
I believe that my mistake is that I don't understand the key concept of data encapsulation, objects, etc. I'd appreciate any help.
Here is the Settings view controller. I'm not even sure how to put the code into this forum so this might be a laughable moment... here goes:
// settings_flashcards.h
#import <UIKit/UIKit.h>
#interface settings_flashcards : UIViewController {
UISwitch *additionSwitch;
UISwitch *subtractionSwitch;
UISwitch *multiplicationSwitch;
UISwitch *divisionSwitch;
}
#property (nonatomic,retain) IBOutlet UISwitch *additionSwitch;
#property (nonatomic,retain) IBOutlet UISwitch *subtractionSwitch;
#property (nonatomic,retain) IBOutlet UISwitch *multiplicationSwitch;
#property (nonatomic,retain) IBOutlet UISwitch *divisionSwitch;
#end
and...
/ settings_flashcards.m
#import "settings_flashcards.h"
#implementation settings_flashcards
#synthesize additionSwitch;
#synthesize subtractionSwitch;
#synthesize multiplicationSwitch;
#synthesize divisionSwitch;
- (void)viewDidLoad {
[additionSwitch addTarget:self action:#selector(additionSwitchFlipped) forControlEvents:UIControlEventValueChanged];
[subtractionSwitch addTarget:self action:#selector(subtractionSwitchFlipped) forControlEvents:UIControlEventValueChanged];
[multiplicationSwitch addTarget:self action:#selector(multiplicationSwitchFlipped) forControlEvents:UIControlEventValueChanged];
[divisionSwitch addTarget:self action:#selector(divisionSwitchFlipped) forControlEvents:UIControlEventValueChanged];
[super viewDidLoad];
}
-(void) additionSwitchFlipped {
if (additionSwitch.on) {
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:#"additionKey"];
}else {
[[NSUserDefaults standardUserDefaults] setBool:FALSE forKey:#"additionKey"];
}
}
-(void) subtractionSwitchFlipped {
if (subtractionSwitch.on) {
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:#"subtractionKey"];
}else {
[[NSUserDefaults standardUserDefaults] setBool:FALSE forKey:#"subtractionKey"];
}
}
-(void) multiplicationSwitchFlipped {
if (multiplicationSwitch.on) {
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:#"multiplicationKey"];
}else {
[[NSUserDefaults standardUserDefaults] setBool:FALSE forKey:#"multiplicationKey"];
}
}
-(void) divisionSwitchFlipped {
if (divisionSwitch.on) {
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:#"divisionKey"];
}else {
[[NSUserDefaults standardUserDefaults] setBool:FALSE forKey:#"divisionKey"];
}
}
Here is the Flashcards view...
// flashcardsViewController.h
#import <UIKit/UIKit.h>
#interface flashcardsViewController : UIViewController <UIActionSheetDelegate>{
UILabel *firstNumberLabel;
UILabel *secondNumberLabel;
UILabel *answerNumberLabel;
UILabel *operatorLabel;
BOOL additionIsEnabled;
BOOL subtractionIsEnabled;
BOOL multiplicationIsEnabled;
BOOL divisionIsEnabled;
}
#property (nonatomic,retain) IBOutlet UILabel *firstNumberLabel;
#property (nonatomic,retain) IBOutlet UILabel *secondNumberLabel;
#property (nonatomic,retain) IBOutlet UILabel *answerNumberLabel;
#property (nonatomic,retain) IBOutlet UILabel *operatorLabel;
-(void) buttonClicked:(id)sender;
#end
and...
// flashcardsViewController.m
#import "flashcardsViewController.h"
#implementation flashcardsViewController
#synthesize firstNumberLabel;
#synthesize secondNumberLabel;
#synthesize answerNumberLabel;
#synthesize operatorLabel;
- (void)viewDidLoad {
srand(time(0)); //seed random
//the following should assign the keys if they don't exist
if (![[NSUserDefaults standardUserDefaults] boolForKey:#"additionKey"]){
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:#"additionKey"];
}
if (![[NSUserDefaults standardUserDefaults] boolForKey:#"subtractionKey"]) {
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:#"subtractionKey"];
}
if (![[NSUserDefaults standardUserDefaults] boolForKey:#"multiplicationKey"]) {
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:#"multiplicationKey"];
}
if (![[NSUserDefaults standardUserDefaults] boolForKey:#"divisionKey"]) {
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:#"divisionKey"];
}
//the following should assign each BOOL variable based on the key
additionIsEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:#"additionKey"];
subtractionIsEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:#"subtractionKey"];
multiplicationIsEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:#"multiplicationKey"];
divisionIsEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:#"divisionKey"];
[super viewDidLoad];
}
-(void) buttonClicked:(id)sender{
int a = rand() % 4;// random number generator (number to enter loop)
if ( additionIsEnabled || subtractionIsEnabled || multiplicationIsEnabled || divisionIsEnabled) {
while (a < 5) {
switch (a) {
case 0:
if (additionIsEnabled == TRUE){
int x = rand() % 11 + 1;
int y = rand() %11 + 1;
firstNumberLabel.text = [[NSString alloc]initWithFormat: #"%i",x];
secondNumberLabel.text = [[NSString alloc]initWithFormat: #"%i",y];
answerNumberLabel.text = [[NSString alloc]initWithFormat: #"%i",(x+y)];
operatorLabel.text = [[NSString alloc]initWithFormat: #"+"];
a = 5;
}
else a++;
break;
case 1:
if (subtractionIsEnabled == TRUE){
int x = rand() % 19 + 1;
int y = rand() %11 + 1;
firstNumberLabel.text = [[NSString alloc]initWithFormat: #"%i",x];
secondNumberLabel.text = [[NSString alloc]initWithFormat: #"%i",y];
answerNumberLabel.text = [[NSString alloc]initWithFormat: #"%i",(x-y) ];
operatorLabel.text = [[NSString alloc]initWithFormat: #"-"];
a = 5;
}
else a++;
break;
case 2:
if (multiplicationIsEnabled == TRUE){
int x = rand() % 11 + 1;
int y = rand() %11 + 1;
firstNumberLabel.text = [[NSString alloc]initWithFormat: #"%i",x];
secondNumberLabel.text = [[NSString alloc]initWithFormat: #"%i",y];
answerNumberLabel.text = [[NSString alloc]initWithFormat: #"%i",(x*y)];
operatorLabel.text = [[NSString alloc]initWithFormat: #"×"];
a = 5;
}
else a++;
break;
case 3:
if (divisionIsEnabled == TRUE){
int x = rand() % 11 + 1;
int y = rand() % 11 + 1;
firstNumberLabel.text = [[NSString alloc]initWithFormat: #"%i",(x*y)];
secondNumberLabel.text = [[NSString alloc]initWithFormat: #"%i",y];
answerNumberLabel.text = [[NSString alloc]initWithFormat: #"%i",x];
operatorLabel.text = [[NSString alloc]initWithFormat: #"÷"];
a = 5;
}
else a = 0;
break;
default:
break;
}
}
}
else
{
UIAlertView *noOperatorSelectedAlert = [[UIAlertView alloc]initWithTitle:#"You have not set any operations."
message:#"Return to the settings menu and decide which operations you wish to perform. (addition, subtraction, etc.)"
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[noOperatorSelectedAlert show];
[noOperatorSelectedAlert release];
}
}
There are a few things to do here. Firstly you want a better way of saying what the default state is before the user has made any explicit decisions. Next you want to know when you should refresh your in-app state from user preferences.
Defaults Initialization
The first item's solution is to put the default values into the registration domain for your user preferences. This is something you'll do during application initialization, rather than having your views individually check preferences and update them at initialization time. The preferences system looks in quite a few places for data, and the first place it looks is in the in-memory-only registration domain. This is where you'll put the default (i.e. no value specified means 'x') values for each of your user preferences.
The API you'll use for this is -[NSUserDefaults registerDefaults:], which takes an NSDictionary of values. To set your default values of YES (in Objective-C the BOOL type uses YES and NO rather than TRUE and FALSE) you'll use something like this, commonly executed in a +initialize method for your application's main class:
+ (void) initialize
{
// in any +initialize, make sure it's being called on your class
// +initialize is different from all other methods in this respect
if ( [self isKindOfClass: [MyApplicationDelegate class]] == NO )
return; // being called on a superclass, don't do my stuff
// set up default values for certain preferences
NSMutableDictionary * defaults = [NSMutableDictionary new];
[defaults setObject: [NSNumber numberWithBool: YES] forKey: #"additionKey"];
[defaults setObject: [NSNumber numberWithBool: YES] forKey: #"subtractionKey"];
[defaults setObject: [NSNumber numberWithBool: YES] forKey: #"multiplicationKey"];
[defaults setObject: [NSNumber numberWithBool: YES] forKey: #"divisionKey"];
// set this as the registration domain
[[NSUserDefaults standardUserDefaults] registerDefaults: defaults];
[defaults release];
}
Usually you'll put everything into one method like this, so if you have other parts of the application which expect a default non-zero value for any preference, you should add those to this group and place it into your application delegate's +initialize method.
Now, when your other classes use [[NSUserDefault standardUserDefaults] boolForKey: #"additionKey"] and there is nothing saved to the preference files for that key, they will get the value supplied above.
Refreshing Cached Values
So, you have a view where the user is able to change these preferences. Your next job is to make the view above that update its member variables using the new preferences. For this we can use either delegation or notification. In this case, I'll go with notifications for to reasons:
You're using NSUserDefaults, which can theoretically change in many different places. Delegation would only inform you of changes made by one object.
NSUserDefaults already implements a handy notification which you can watch.
So, in your flashcardsViewController you'll have something like these few methods:
- (void) updateFromPreferences
{
// fetch current values from user defaults into your member variables
additionIsEnabled = [[NSUserDefaults standardUserDefaults] boolForKey: #"additionKey"];
// etc...
}
- (void) viewWillLoad
{
// load variables from user defaults
[self updateFromPreferences];
// find out when the preferences have been changed
// this will cause -updateFromPreferences to be called
// whenever something changes preferences, inside the app or outside
[[NSNotificationCenter defaultNotificationCenter] addObserver: self
selector: #selector(updateFromPreferences)
name: NSUserDefaultsDidChangeNotification
object: nil];
}
- (void) viewDidUnload
{
// always remove notification observers.
[[NSNotificationCenter defaultNotificationCenter] removeObserver: self
name: NSUserDefaultsDidChangeNotification
object: nil];
}
- (void) dealloc
{
// add this to your existing dealloc routine
[[NSNotificationCenter defaultNotificationCenter] removeObserver: self
name: NSUserDefaultsDidChangeNotification
object: nil];
}
Summary
Taken together, these two should give you everything you need to make this work.
In addition to the "always YES" problem pointed out by Chiefly Izzy, your -buttonClicked: method does not read new values from NSUserDefaults. These values are read (once) in [flashcardsViewController viewDidLoad]. If they are changed in settings, the change will not be detected in flashCardsViewController until the next time it is loaded (probably the next time the application is launched).
The simplest approach would be to move your code for reading the IsEnabled BOOL values into the -buttonClicked method, like so:
-(void) buttonClicked:(id)sender {
// the following should assign each BOOL variable based on the key
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
additionIsEnabled = [defaults boolForKey:#"additionKey"];
subtractionIsEnabled = [defaults boolForKey:#"subtractionKey"];
multiplicationIsEnabled = [defaults boolForKey:#"multiplicationKey"];
divisionIsEnabled = [defaults boolForKey:#"divisionKey"];
int a = rand() % 4;
if ( additionIsEnabled || subtractionIsEnabled ...
This code ...
//the following should assign the keys if they don't exist
if (![[NSUserDefaults standardUserDefaults] boolForKey:#"additionKey"]){
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:#"additionKey"];
}
... simply always set's additionKey to TRUE. If you would like to check if additionKey is set, do this ...
//the following should assign the keys if they don't exist
if (![[NSUserDefaults standardUserDefaults] objectForKey:#"additionKey"]){
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:#"additionKey"];
}
... boolForKey: documentation: If a boolean value is associated with defaultName in the user defaults, that value is returned. Otherwise, NO is returned.
Translated to human language - if there's an value associated with additionKey, this value is returned. If there's no associated value, NO/FALSE is returned.
So, your code does this - if value is not associated with additionKey or if it is set to NO, set it to YES. This leads to this - additionKey is always set to YES/TRUE.

How to store a float in NSUserDefaults

I want to store a float value into NSUserDefaults.
I also need to check that the float value exists..if not I need to assign some value in it.
and retrieve it...for the above I have the below code but it gives me an error.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults boolForKey:#"HANDWRITING_SIZE_SLIDER"] == YES) {
self.sizeSlider.value = 10.0;
} else {
self.sizeSlider.value = [[NSUserDefaults standardUserDefaults] floatForKey:#"HANDWRITING_SIZE_SLIDER"]];
}
Thanks for any help
Use the NSNumber class for this and store it via the setObject:forKey: method so you can check if it exists.
I'd also suggest the usage of constants as keys:
#define HANDWRITING_SIZE_SLIDER #"HSS"
Your code should be along these lines:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:HANDWRITING_SIZE_SLIDER] == nil) {
//doesn't exist in NSUserDefaults, set to default value...
self.sizeSlider.value = 10.0;
} else {
self.sizeSlider.value = [[defaults objectForKey:HANDWRITING_SIZE_SLIDER] floatValue];
}
Somewhere else in your app, you'd set the value in NSUserDefaults like this:
float sizeSliderValue = ...
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithFloat:sizeSliderValue] forKey:HANDWRITING_SIZE_SLIDER];
Try this code:
-(IBAction)sliderAction:(id)sender
{
float sliderValue = [sender floatValue];
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithFloat:sliderValue] forKey:#"keySliderValue"];
NSLog(#"%#",[[NSUserDefaults standardUserDefaults] objectForKey:#"keySliderValue"]);
}

should variable be released or not? iphone-sdk

I have the following piece of code from a book.
There is this function loadPrefs where the NSString *userTimeZone is being released before the end of the function.
Why? The string was not created with alloc and I assume that the stringForKey function returns an autoreleased NSString. Is this an error or am I missing something? Is it an error in the book? (I new into objective-C)
In the documentation for stringForKey the only thing it mentions is:
Special Considerations
The returned
string is immutable, even if the value
you originally set was a mutable
string.
The code:
- (void) loadPrefs {
timeZoneName = DefaultTimeZonePref;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *userTimeZone = [defaults stringForKey: TimeZonePrefKey];
if (userTimeZone != NULL)
timeZoneName = userTimeZone;
[userTimeZone release];
show24Hour = [defaults boolForKey:TwentyFourHourPrefKey];
}
Thanks!!!!
You're right. There are two things wrong with this code: it's releasing the string from stringForKey: improperly, and it's not retaining userTimeZone when it assigns the value to an instance variable.
Here's a better attempt:
- (void) loadPrefs {
[timeZoneName release]; // In case there was a previous value
timeZoneName = DefaultTimeZonePref; // ASSUMPTION: DefaultTimeZonePref is a constant
// And thus doesn't need retain/release.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *userTimeZone = [defaults stringForKey: TimeZonePrefKey];
if (userTimeZone != NULL) {
timeZoneName = [userTimeZone retain];
}
show24Hour = [defaults boolForKey:TwentyFourHourPrefKey];
}
And don't forget to release timeZoneName in dealloc.