【问题标题】:Objective-C – Delegate is dealloced?Objective-C – 委托被解除分配?
【发布时间】:2011-07-31 08:51:11
【问题描述】:

我有一个视图控制器,它列出了UITableView 中的一些数据。为了下载数据,我使用 ASIHTTPRequest 我在另一个类中放置了哪些方法。

在我的视图控制器中,我设置了适当的委托来处理从ASIHTTPRequest 检索的数据。因此,从- viewDidLoad 的视图控制器中,我分配并初始化我的类,该类包含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

我在这里做错了什么?

【问题讨论】:

    标签: objective-c delegates uiviewcontroller


    【解决方案1】:

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

    【讨论】:

    • 那么这篇文章中所说的“错误”是什么? stackoverflow.com/questions/3924484/…
    • @Peter Warbo:是的,其他问题没有正确处理内存管理(除非它是保留属性)。
    • @Peter Warbo:好吧,如果它立即发布,我不希望它起作用。但我检查了 NSXMLParser (developer.apple.com/library/ios/#documentation/Cocoa/Reference/…) 的文档,它在 setDelegate 实例方法中说明了以下内容:“委托:一个作为新委托的对象。它没有被保留。”
    • 那么,我将如何正确处理我的 vc 对象内存?我应该autorelease吗?
    • 这取决于你,真的。但有时autorelease 可能为时过早。您可以做的一件事是将 vc 设置为具有保留策略的另一个属性(然后您将在 -dealloc 中发出释放调用)。
    猜你喜欢
    • 1970-01-01
    • 2013-08-12
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多