目标 C:在这种情况下如何释放代表
我正在使用自定义委托对象在请求完成后执行一些清理任务。 ASIHTTPRequest 不保留委托,因此我无法自动释放它们。现在这就是我分配和释放代表的方式。
App Delegate
MyDelegate *delegate = [[MyDelegate alloc] init];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:delegate];
MyDelegate.m
- (void)requestFinished:(ASIHTTPRequest *)request
{
[self release];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
[self release];
}
有更好的方法吗?让代表自行释放似乎很丑陋,而且 Xcode 的构建和分析对我正在做的事情感到不舒服。
I am using custom delegate objects to do some cleanup tasks after a request finishes. ASIHTTPRequest doesn't retain delegates so I can't autorelease them. Right now this is how I am allocating and releasing the delegates.
App Delegate
MyDelegate *delegate = [[MyDelegate alloc] init];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:delegate];
MyDelegate.m
- (void)requestFinished:(ASIHTTPRequest *)request
{
[self release];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
[self release];
}
Is there a better way to do this? Having the delegates release themselves seems ugly and Xcode's build and analyze feels uncomfortable with what I'm doing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一种简单的方法是为主控制器(在本例中为应用程序委托)中的每个活动请求维护一组可变委托:
A simple approach would be to maintain a mutable set of delgates for each active request in your main controller (the app delegate, in this case):
为什么你有一个单独的类纯粹是为了当代表?这不是委托对象通常的工作方式。通常,创建 ASIHTTPRequest 的控制器成为委托,此时您不必担心释放它,因为它已经比 ASIHTTPRequest 的寿命更长(并且如果您的控制器在 ASIHTTPRequest 完成之前被释放,您需要取消该请求)。
Why do you have a separate class purely to be a delegate? That's not how delegate objects typically work. Normally the controller that created the ASIHTTPRequest becomes the delegate, at which point you don't have to worry about releasing it because it will outlive the ASIHTTPRequest already (and if your controller gets dealloced before the ASIHTTPRequest is done, you need to cancel the request).
如果您不想为所有委托实例创建“控制器”类,我仍然至少会遵循内存约定规则,并在将委托设置为 asihhtprequest 后立即释放委托。然后我会在委托中包含一个属性,名称为managesItsOwnLifetime(BOOL),并将其设置为YES时我会执行[自我保留]...
If You don't want to create a "controller" class for all your delegate instances, i would still at least follow the memory convention rules, and release the delegate immediately after setting it to asihhtprequest. Then i would include a propery in the delegate, something with a name managesItsOwnLifetime (BOOL) and on setting this to YES i would do a [self retain] ...