【问题标题】:Releasing memory allocated in class method initialize释放在类方法初始化中分配的内存
【发布时间】:2010-10-28 16:02:29
【问题描述】:

我在类方法initialize中分配内存:

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

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

【问题讨论】:

    标签: iphone objective-c


    【解决方案1】:

    在您提供的示例中,我不会费心清理。内存量非常小,唯一适合清理的地方是应用程序退出时,此时您真的不再关心这些对象了。

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

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

    然后你就有了有用的小辅助方法,不需要这些对象停留在周围。确保颜色是否保留是调用者的责任。

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

    【讨论】:

    • 感谢您的回复。这是一个很好的建议。我也考虑过这样做是为了解决分配问题,但考虑了在每个请求上分配的性能与返回已创建的实例的性能。由于这是一个低使用(目前)分配每个调用不应该有影响。返回与我原来相同的实例的一个缺点是调用者可以修改实例 - 您建议的方法可以缓解这种情况。
    【解决方案2】:

    没有一个,所以你不会释放那个内存;当您的进程退出时,操作系统会回收它。一旦加载并初始化,该类将在整个过程的执行过程中持续存在(除非有人调用-[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);
        }
    }
    

    【讨论】:

    • 如果分配和返回相同的实例,延迟加载肯定是更好的方法 - 感谢您的回答/建议。
    猜你喜欢
    • 2015-11-08
    • 2012-01-22
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多