你的成语是避免"远程"发布的"潜在泄漏"警告吗?

Fat*_*tie 2 iphone memory-management clang autorelease ios

处理大型图像的动画,您可以这样做:只需为每个大图像分配内存......

NSArray *imagesForLargeAnimation;

#define IMG(X) [[UIImage alloc] \
  initWithContentsOfFile:[[NSBundle mainBundle] \
    pathForResource:@X ofType:@"tif"]]

imagesForLargeAnimation  = [[NSArray alloc] initWithObjects:
                    IMG("01"),
// (since we are allocing that image, of course we must release it eventually.)
                    IMG("02"),
                    IMG("03"),
                    ....
                    IMG("42"),
                    nil];

animationArea.animationImages = imagesForLargeAnimation;
//blah blah...
Run Code Online (Sandbox Code Playgroud)

之后,一旦动画停止并且不再显示在屏幕上,要清理内存,您必须执行此操作:

-(void) cleanUpTheMemoryInTheBigAnimation
 {
 //blah blah..

 // for each of those big images in the array, release the memory:
 for (UIImage *uu in imagesForLargeAnimation)
    [uu release];

 // release the array itself
 [imagesForLargeAnimation release];
 imagesForLargeAnimation = nil;
Run Code Online (Sandbox Code Playgroud)

现在,这一切都完美有效地工作,如果你反复使用不同的大型动画,它不会泄漏也不会过度使用内存.

唯一的问题是,当然你得到了clang警告:"在第69行分配的对象的潜在泄漏",实际上你得到了这些警告的分数,每个分配一个.

什么是避免这些警告的最佳成语 - 并使其更安全,更紧凑?

有人知道吗?

例如,如果您使用自动释放,那么,在上面的代码示例中,您将在IMG定义中使用自动释放...

...实际上,当你释放NSArray时(即[imagesForLargeAnimation发布])......那时它会自动释放数组中的所有对象吗?那是对的吗?要么??

(或者我应该使用某种newBlah函数来放入图像,或者?? ??)

如果有人知道这里的正确方法,以避免"潜在泄漏",谢谢!

{PS提醒基本上从不使用imageNamed:,它没有希望:它只适用于小型UI使用类型的图像.永远不要使用imageNamed!}

dea*_*rne 6

您不需要保留图像 - NSArray将为您执行此操作.

试试这个 :

#define IMG(X) [[[UIImage alloc] \
  initWithContentsOfFile:[[NSBundle mainBundle] \
    pathForResource:@X ofType:@"tif"]] autorelease]
Run Code Online (Sandbox Code Playgroud)

你现在不需要这个代码:

// for each of those big images in the array, release the memory:
//for (UIImage *uu in imagesForLargeAnimation)
//    [uu release];
Run Code Online (Sandbox Code Playgroud)

仅供参考(1):

如果您使用imageNamed,您将不会收到警告,因为imageNamed返回已经自动释放的对象,但alloc/initWithcontentsOfFile没有:)


仅供参考(2):

NSArrays上有一个方法,它在所有对象上执行选择器:

[imagesForLargeAnimation makeObjectsPerformSelector:@selector(release)];
Run Code Online (Sandbox Code Playgroud)