Objective-C – 委托(delegate)被释放?

标签 objective-c delegates uiviewcontroller

我有一个 View Controller ,它列出了 UITableView 中的一些数据。为了下载数据,我使用 ASIHTTPRequest 我已将其方法放入另一个类中。

在我的 View Controller 中,我设置了适当的委托(delegate)来处理从 ASIHTTPRequest 检索的数据。因此,从 - viewDidLoad 中的 View Controller 中,我分配并初始化包含 ASIHTTPRequest 方法的类,如下所示:

self.officesParser = [[[OfficesParser alloc] init] autorelease]; // retained property

然后在 - viewDidAppear: 中调用 [officesParser downloadOffices];

我的 - downloadOffices 方法如下所示:

- (void)downloadOffices {

    // 1. Downloaded offices.json
    NSURL *officesUrl = [NSURL URLWithString:@"http://example.com/example.json"];
    ASIHTTPRequest *officesRequest = [ASIHTTPRequest requestWithURL:officesUrl];

    // Always ask the server if there is new content available, 
    // If the request fails, use data from the cache even if it should have expired.
    [officesRequest setCachePolicy:ASIAskServerIfModifiedCachePolicy|ASIFallbackToCacheIfLoadFailsCachePolicy];

    // Store the cache permanently
    [officesRequest setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];

    [officesRequest setTag:1];

    OfficesViewController *vc = [[OfficesViewController alloc] init];
    [officesRequest setDelegate:vc];
    [vc release];
    [officesRequest startAsynchronous];
}

每次调用 [officesParser downloadOffices] 方法后我都会得到:

*** -[OfficesViewController respondsToSelector:]: message sent to deallocated instance 0x6a2f6c0

我在这里做错了什么?

最佳答案

您希望 vc 成为 officesRequest 的委托(delegate),但是,在分配并初始化 vc 并将其设置为委托(delegate)之后,您立即释放它。请注意,委托(delegate)属性通常是分配,而不是保留。然后,您负责保持委托(delegate)对象的存在,直到不再需要为止。因此,如果您打算在不久的将来向它发送消息,则无法立即释放它。

关于Objective-C – 委托(delegate)被释放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6888443/

相关文章:

iphone - NSUserDefaults 中的 NSDate 问题

ios - 弱委托(delegate)变为零

c# - 使用委托(delegate)调用 Lambda 表达式的语法

iphone - UILabel 未更新与 IBOutlet 连接

iphone - 以编程方式创建 UISwitch

objective-c - 如何在之前放置为 MKPinAnnotationView 的 leftCalloutAccessoryView 的按钮下添加文本

C# 从委托(delegate)函数访问所有者对象

ios - 从 View 过渡 :toView:duration:options:completion: confusion

xcode - 复制/粘贴时 View Controller 变小(Xcode 7、Swift 2)

ios - 如何强制 UIView 的 layoutSubviews?