[英]cocoa memory management question
I am in an argument with a friend who says that I have to put autorelase here: 我与一个朋友争论,他说我必须在此处放置自动释放:
NSURL *url = [[NSURL URLWithString:@"http://origin-www.metrolyrics.com/api/widgets/mac/seeker.php"] autorelease];
But isn't the object automatically autoreleased when it was send to me from NSURL class method? 但是,从NSURL类方法发送给我的对象不是自动自动释放的吗? Thanks.
谢谢。
This is the rule: 这是规则:
If you invoke a method that returns an object and: 如果调用返回对象的方法,并且:
new
new
开始 alloc
alloc
开始 retain
retain
copy
copy
then you are responsible for releasing (or autoreleasing) the returned object. 那么您有责任释放(或自动释放)返回的对象。 The only time this would not be the case is if the documentation says otherwise.
唯一不是这样的情况是,如果文档中另有说明。 You may also see in the header files that the method is annotated with the
NS_RETURNS_RETAINED
macro. 您可能还会在头文件中看到该方法使用
NS_RETURNS_RETAINED
宏进行了注释。 (The header file counts as documentation) (头文件算作文档)
An easy way to remember this is "NARC" (new-alloc-retain-copy). 一种简单的记住方式是“ NARC”(new-alloc-retain-copy)。
In your example, since URLWithString:
does not begin with new
or alloc
, does not contain copy
, and is not retain
, then you must not release the returned object. 在您的示例中,由于
URLWithString:
不以new
或alloc
开头,不包含copy
,也不retain
,因此您不得释放返回的对象。 Doing so is a violation of the memory management guidelines and will cause your app to crash (unless you're doing something stupid elsewhere). 这样做违反了内存管理准则,并且会导致您的应用崩溃(除非您在其他地方做蠢事)。
You are right. 你是对的。 you did not allocate or copy an object so you do not have to release it.
你没分配或复制的对象,所以你不必释放它。 Just use your code without the autorelease.
只需使用您的代码而无需自动发布。 ;-)
;-)
The Class method you used looks like this: (Normally it does. We can't know it, because Apple doesn't share the code.) 您使用的Class方法如下所示:(通常是这样。我们不知道,因为Apple不共享代码。)
+(id)URLWithString:(NSString *)aString {
return [[[self alloc] initWithString:aString] autorelease];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.