我什么时候应该在 Objective-C 中释放这些对象?
我是 obj-c 编程新手。那么,我什么时候释放定义的对象呢? 我必须释放 urlRequest、响应、数据和内容吗?
- (NSString*)getContentFromUrl:(NSURL*)url {
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] init];
[urlRequest setHTTPMethod:@"GET"];
[urlRequest setURL:url];
NSHTTPURLResponse *response = NULL;
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:nil];
NSString *content = NULL;
if ([response statusCode] >= 200) {
content = [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding];
}
[content autorelease];
return content;
}
I'm new in programming obj-c. So, when shall i release the defined objects?
Do i have to release urlRequest, response, data and content?
- (NSString*)getContentFromUrl:(NSURL*)url {
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] init];
[urlRequest setHTTPMethod:@"GET"];
[urlRequest setURL:url];
NSHTTPURLResponse *response = NULL;
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:nil];
NSString *content = NULL;
if ([response statusCode] >= 200) {
content = [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding];
}
[content autorelease];
return content;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只需释放
urlRequest
。response
、data
已作为自动释放对象创建,并且content
在返回之前接收自动释放消息(我建议仅使用更改最后两行>返回[内容自动释放]
)。将对象指针初始化为
nil
而不是NULL
也更常见。Cocoa 有一个约定,如果您在初始化或重新分配时对任何对象调用
alloc
、copy
、retain
或new
您必须release
它们,除非它们在创建后收到autorelease
消息。您可以从代码中看到,只有
urlRequest
和content
变量是使用alloc
方法创建的,因此必须[auto]释放它们。更新注意评论
如果您将
urlRequest
作为实例变量,则先前启动的变量可能会影响ivar,并且您可能会遇到各种麻烦(例如EXC_BAD_ACCESS)。您最好为局部变量选择一个不同的名称。
You have to release
urlRequest
only.response
,data
are created already as autoreleased objects andcontent
receives autorelease message before return (I'd suggest changing last two lines with justreturn [content autorelease]
).It's also more common to initialize object pointers to
nil
rather thanNULL
.Cocoa has a convention if you call
alloc
,copy
,retain
ornew
on any of objects while initializing or reassigning them you have torelease
them unless they receiveautorelease
message after creation.You can see from your code that only
urlRequest
andcontent
variables are created usingalloc
method, hence they have to be [auto]released.update minding the comments
If you have
urlRequest
as an instance variable the previously initiated variable can shadow the ivar and you may get into various troubles (likeEXC_BAD_ACCESS
). You better pick a different name for your local variable.