0

i am working my way through David Mark et al's More iOS6 Development book, and am puzzled by an issue related to declaring a static NSDateFormatter instance within a tableviewcell class.

in the example program, at one point they have the reader create a tableviewcell class for creating a cell object used for inputting a date. they advise declaration of a static NSDateFormatter instance within that tableviewcell class. they explain the rationale as follows: "What have you done here? You defined a local static variable __dateFormatter of type NSDateFormatter. You’re doing this because creating an NSDateFormatter is an expensive operation, and you don’t want to have to create a new instance every time you want to format a an NSDate"

the code is as follows:

#import "SuperDBDateCell.h"
static NSDateFormatter *__dateFormatter = nil;
@interface SuperDBDateCell ()
@property (strong, nonatomic) UIDatePicker *datePicker;
- (IBAction)datePickerChanged:(id)sender;
@end
@implementation SuperDBDateCell
+ (void)initialize
{
    __dateFormatter = [[NSDateFormatter alloc] init];
    [__dateFormatter setDateStyle:NSDateFormatterMediumStyle];
}

what i do not understand is what happens to the instance _dateFormatter when the view that contains this tableviewcell disappears...that is, is not this static variable deallocated at that time, and then re-created each time the parent view containing an instance of this tableviewcell class is re-created? if not, why not?

thanks for any help...i've been looking through SO, and the apple developer site as well and haven't been able to find anything yet that explains it...

4

1 回答 1

2

The initialize class method will only be called once during the lifetime of the app. So the static __dateFormatter will be initialized one time. It will never be deallocated during the lifetime of the app. That's the point of a static variable. It is not tied in any way to an instance of the class. It exists outside the scope of any instance.

Unless you add code to explicitly set __dateFormatter to nil or assign a new data formatter, its value will stay in place.

Side note - there is one problem with using such code. If the user puts your app in the background, and then changes the Region Format setting in the Settings app, and returns to your app, this date formatter will still use the old formatting. Whenever you have a class with formatters, ideally you should listen for NSCurrentLocaleDidChangeNotification notifications so you can update any long lived formatters to reflect the new locale.

于 2013-07-19T20:58:26.193 回答