简体   繁体   English

什么是将UIImage分配给内存并将其释放到iphone的正确方法

[英]Whats the correct way to alloc a UIImage to memory and release it iphone

Using Instruments, I keep on getting pointed to a memory leak with a UIImage. 使用Instruments,我继续使用UIImage指向内存泄漏。
I think I'm assigning and releasing the memory correctly. 我想我正在分配和释放内存。 The leaked object in instruments is described as NSConcreteData 仪器中泄漏的物体被描述为NSConcreteData

Is the following the correct way to assign and release a UIImage? 以下是分配和释放UIImage的正确方法吗?

UIImage* flagimg = [UIImage imageWithData: [NSData dataWithContentsOfURL:url2]];    
[flagimg release];
flagimg =nil;

[UIImage imageWithData:] returns an autoreleased object, which should not be released by you again. [UIImage imageWithData:]返回一个自动释放的对象,不应该再次释放它。 So this code snipped contains not a memory leak but the opposite, a double free (in the worst case). 因此,这段代码剪切不包含内存泄漏,但相反,双重免费(在最坏的情况下)。

Note that Instruments sometimes generates false positives and/or reports memory leaks in the Foundation itself (yep, they make mistakes too :-). 请注意,仪器有时会在基金会本身产生误报和/或报告内存泄漏(是的,它们也会犯错误:-)。

The fastest way to alloc/release an object is to avoid convenience initializers (like imageWithData:) and instead to something like 分配/释放对象的最快方法是避免使用便利初始化程序(如imageWithData :),而不是像

NSData* data = [[NSData alloc] initWithContentsOfURL:url]];
UIImage* img = [[UIImage alloc] initWithData:data];
[data release];
// use your image
[img release];

This will allocate and release your object right away and not wait until the autorelease pool is cleaned. 这将立即分配和释放您的对象,而不是等到清理自动释放池。

But please note too, that a memory leak is generally not memory that is not yet freed, but that is lost and cannot be freed anymore , so an object which will be deallocated by the autorelease pool is not considered a memory leak. 但是请注意,内存泄漏通常不是尚未释放的内存,但是丢失并且不能再释放 ,因此将被自动释放池释放的对象不被视为内存泄漏。

as a general rule you can say 作为一般规则,你可以说

if you create an object an theres a "init","copy" or "retain" in it, you have to release it. 如果您创建一个对象,其中包含“init”,“copy”或“retain”,则必须将其释放。 if not, you get an autoreleased object. 如果没有,你得到一个自动释放的对象。

thats not always true, but in most cases 这并非总是如此,但在大多数情况下

both imageWithData and dataWithContentsOfURL return autoreleased objects, so you should have no memory leaks in that code snippet. imageWithDatadataWithContentsOfURL返回自动释放的对象,因此您应该在该代码段中没有内存泄漏。

Since flagimg is returned autoreleased, your [flagimg release]; 由于flagimg是自动释放的,你的[flagimg release]; call is not needed; 不需要打电话; you're over-releasing that object. 你过度释放那个物体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM