-1

这是我的代码。

#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() ?

导致状态是一个未分配的静态变量,编译器自动找到一个方法来初始化它?

4

1 回答 1

2

每当将静态类添加到运行时时都会调用 load 函数,因此发生在您身上的是正常行为,如果您希望不调用函数,请将其命名为其他

来自苹果文档

每当将类或类别添加到 Objective-C 运行时时调用;实现此方法以在加载时执行特定于类的行为。

于 2012-06-25T07:15:57.150 回答