gpt4 book ai didi

objective-c - Objective-C : How to release delegates in this situation

转载 作者:太空狗 更新时间:2023-10-30 03:50:18 25 4
gpt4 key购买 nike

我正在使用自定义委托(delegate)对象在请求完成后执行一些清理任务。 ASIHTTPRequest 不保留委托(delegate),所以我不能自动释放它们。现在这就是我分配和释放委托(delegate)的方式。

应用委托(delegate)

MyDelegate *delegate = [[MyDelegate alloc] init];   
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:delegate];

我的委托(delegate).m

- (void)requestFinished:(ASIHTTPRequest *)request
{
[self release];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
[self release];
}

有更好的方法吗?让委托(delegate)释放自己看起来很丑陋,Xcode 的构建和分析对我正在做的事情感到不舒服。

最佳答案

一种简单的方法是为主 Controller 中的每个事件请求维护一组可变委托(delegate)(在本例中为应用程序委托(delegate)):

@interface MyAppController
{
NSMutableSet * activeDelegates;
}
@end

@implementation MyAppController

- (id)init
{
if ((self = [super init]) == nil) { return nil; }
activeDelegates = [[NSMutableSet alloc] initWithCapacity:0];
return self;
}

- (void)dealloc
{
[activeDelegates release];
}

- (void)createRequest
{
MyDelegate *delegate = [[MyDelegate alloc] init];
[activeDelegates addObject:delegate];
[delegate release];

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];

...
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
MyDelegate *delegate = [request delegate];
[delegate doSomething];
[activeDelegates removeObject:delegate];
{

- (void)requestFailed:(ASIHTTPRequest *)request
{
[activeDelegates removeObject:[request delegate]];
}

@end

关于objective-c - Objective-C : How to release delegates in this situation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4609676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com