释放在类方法初始化中分配的内存

时间:2010-10-28 16:02:30

标签: iphone objective-c

我在类方法初始化中分配内存:

UIColor * customBlue;
UIColor * customRed;

@implementation UIColorConstants

+ (void)initialize{
 if ( self == [UIColorConstants class] ) { 
  customBlue = [[UIColor alloc]initWithRed:0 green:0.137 blue:0.584 alpha:1];
  customRed = [[UIColor alloc]initWithRed:.91 green:0.067 blue:0.176 alpha:1];
 }
}

+ (UIColor *)getCustomRed{
 return customRed;
}

+ (UIColor *)getCustomBlue{
 return customBlue;
}

@end

释放已分配内存的最佳/正确位置在哪里,因为没有对应的自动调用初始化?

2 个答案:

答案 0 :(得分:4)

在你给出的例子中,我不打扰清理。内存量非常小,清理的唯一适当位置是应用程序退出时,此时你真的不再关心这些对象了。

你可能会考虑的一件事就是不要保持这些颜色,只需这样做:

+ (UIColor*) customRedColor {
    return [[[UIColor alloc]initWithRed:0 green:0.137 blue:0.584 alpha:1] autorelease];
}

然后你有一些有用的小助手方法,它们不需要那些对象。只是呼叫者有责任确保颜色是否保留。

在iOS 4.0多任务处理环境中,这可能也是更好,更简单的行为。

答案 1 :(得分:3)

没有一个,所以你不释放那个记忆;当您的进程退出时,操作系统会回收它。加载并初始化后,该类会在整个过程执行过程中持续存在(禁止某人调用-[NSBundle unload])。预计班级数据将保持相同的持续时间。

如果您有很多班级数据,可以尝试懒惰地初始化它,例如:

+ (UIColor *)getCustomBlue {
    static UIColor *customBlue = nil;
    if (!customBlue) customBlue = [[UIColor alloc] initWithRed:0.0 green:0.137 blue:0.584 alpha:1.0];
    return customBlue;
}
在请求之前,不会创建

customBlue。如果没有人使用它,那么它永远不会被创建,并且永远不会使用任何堆内存。

ETA: St3fan是正确的,你也可以按需创建一个新的自动释放颜色。如果创作成本低廉,这可能是最好的选择。

如果您的某个资源由于某种原因无法被操作系统回收,您可以使用atexit()注册一个出口处理程序来执行清理:

static void
CleanupColors(void) {
    [customBlue release], customBlue = nil;
    [customRed release], customRed = nil;
}

+ (void)initialize {
    if (...) {
        ...
        atexit(CleanupColors);
    }
}
相关问题