开发者

autorelease keyword

开发者 https://www.devze.com 2023-03-29 00:18 出处:网络
I\'m new at objective c 2.0. I ran into this keyword autorelease and I just need some clarifications.I was just wondering what is the difference between the two lines of code below in objective - c 2.

I'm new at objective c 2.0. I ran into this keyword autorelease and I just need some clarifications. I was just wondering what is the difference between the two lines of code below in objective - c 2.0 (thanks in advance):

  1. [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];

  2. [[UIImage ima开发者_运维百科geWithData:[NSData dataWithContentsOfURL:url]] autorelease];


The second line is incorrect. +imageWithData: already returns an autoreleased object. Autoreleasing is effectively like releasing, except you still have ownership of the object until it goes out of scope. Read the Memory Management Programming Guide for more information.

Also note that in ARC you won't be allowed to use this method, the compiler will do it for you.


autorelease is not a keyword, it's a method, it means that this specific object that received the call was added to the current auto release pool ( which is usually created by Cocoa himself while executing events) and once the pool is drained this object will be released from memory so you don't have to care about doing an explicit release.

If you did not have this call you would have to release this object by yourself once you finished using it.

By using autorelease you should make sure there is an auto-release pool currently available, as if there isn't one your object will leak and it's memory will not be claimed. Usually, when you're dealing with events from Cocoa components you can rely on this, otherwise you should create your own auto-release pool. For more information refer to the oficial Apple documentation about it.

Also, you should not call autorelease in an object you have not created with alloc, it's a common behavior on Cocoa based libraries to have method initializations that auto-release objects, so, any method that creates an object but does not include alloc or copy usually means that the object has already been autoreleased and you should not call it again.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号