views:

49

answers:

1

Hi, 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!!!!

A: 

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.

Adam Ernst
Doesn't retaining userTimeZone depend on how it's declared in the class definition?
Nathan S.
It is defined as an instance variable. No property, no setter or getter. Just inside the interface **NSString *timeZoneName;**
psebos
Nathan: I think you're referring to the "assign", "retain", and "copy" options for a property declaration. In this case it's a simple instance variable so you don't have to worry about that.
Adam Ernst