释放内存初始化
我在类中的方法分配内存初始化:释放内存初始化
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
哪里是释放所分配的内存,因为没有对应的初始化自动调用最好/正确的位置?
没有一个,所以你不释放内存;当您的进程退出时,操作系统会回收它。一旦被加载并初始化,该类将在整个执行过程中保持不变(禁止有人呼叫-[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是正确的,你也可以创建一个新的自动发布的颜色点播。如果创作成本低廉,这可能是最好的做法。
如果你有这样不会因OS由于某种原因被回收的资源,你可以注册使用atexit()
进行清理一个在退出处理程序:
static void
CleanupColors(void) {
[customBlue release], customBlue = nil;
[customRed release], customRed = nil;
}
+ (void)initialize {
if (...) {
...
atexit(CleanupColors);
}
}
在你给的例子中,我不会打扰清理。内存的数量非常小,唯一适合清理的地方是应用程序退出时的情况,此时您确实不再关心这些对象。你可能会考虑
有一件事是不保持周围的颜色和简单的事:
+ (UIColor*) customRedColor {
return [[[UIColor alloc]initWithRed:0 green:0.137 blue:0.584 alpha:1] autorelease];
}
然后你不需要这些对象留下来有用的小帮手方法。这只是调用者的责任,以确保颜色保留与否。
这可能也是iOS 4.0多任务环境中更好更简单的行为。
谢谢您的答复。这是一个很好的建议。我也考虑过这个来解决分配问题,但是考虑了每个请求的分配性能和返回已经创建的实例的性能。由于这是一个低用途(现在)分配每个电话不应该有影响。返回与我原来一样的实例的一个缺点是调用者可能会修改该实例 - 您建议的方法会缓解这种情况。 – 2010-10-28 16:32:20
+1我以前没有听说过'atexit'。整齐! – 2010-10-28 16:25:54
如果分配和返回同一个实例,延迟加载肯定是一种更好的方法 - 谢谢你的回答/建议。 – 2010-10-28 16:44:25