这是我的代码。
#import "States.h"
@interface States ()
+ (NSString *)statesFilePath;
@end
static NSMutableDictionary *states = nil;
@implementation States
+ (NSString *)statesFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *statesFilePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:gStatesFile];
return statesFilePath;
}
+ (void)load
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[states release];
NSString *filePath = [[States statesFilePath] retain];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
states = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
} else {
states = [[NSMutableDictionary dictionaryWithObject:[NSNumber numberWithInt:0] forKey:@"ID"] retain];
}
[filePath release];
[pool release];
}
我知道静态变体中的存储状态不是一个好主意。
但我的问题是:为什么每次应用启动时都会自动执行 load() ?
导致状态是一个未分配的静态变量,编译器自动找到一个方法来初始化它?