【发布时间】:2012-03-25 13:45:50
【问题描述】:
我遇到了一个不知道如何解决的问题。让我给出一些相关的代码。
FrontpageViewController (viewDidLoad)
NewsFetcher *newsFetcher = [[NewsFetcher alloc] initWithURL:url];
newsFetcher.delegate = self;
[newsFetcher loadData];
NewsFetcher.h
@property (nonatomic, unsafe_unretained) id <NewsFetcherDelegate> delegate;
我使用 unsafe_unretained 是因为我希望我的应用也能在 iOS 4 上运行,同时为了方便起见仍使用 ARC。
NewsFetcher.m
- (id)initWithURL:(NSURL *)url {
self = [super init];
if (self) {
self.url = url;
self.receivedData = [[NSData alloc] init];
}
return self;
}
- (void)loadData {
NSLog(@"%@", self.delegate); // FrontpageViewController, as expected
NSURLRequest *request = [NSURLRequest requestWithURL:self.url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:15];
if (self.connectionInProgress)
[self.connectionInProgress cancel];
self.connectionInProgress = [[NSURLConnection alloc] initWithRequest:request
delegate:self
startImmediately:YES];
}
这一切都很好。 NewsFetcher 符合 NSURLConnectionDelegate 协议,所以下一个被调用的方法是connection:didReceiveData:。但是,当我在该方法中执行另一个 NSLog(@"%@", self.delegate) 时,我会得到不同的结果(EXEC_BAD_ACCESS、NSCFDictionary 等)。我认为这意味着我的 delegate 属性指向一个已释放的对象,这很奇怪,因为它应该是仍在屏幕上的视图控制器(因此不能被释放,对吧?)。
我的委托如何在一种方法中可用,但在下一种方法中不再可用?和unsafe_unretained有关系吗?
【问题讨论】:
标签: objective-c ios