【发布时间】:2011-09-13 14:56:33
【问题描述】:
我已经实现了在 Nueburg 的 Programming ios 4 中定义的 MyDownloader 类。当我运行代码时,我在 super dealloc 上获得了一个 exc_bad_access。这本书没有提供关于头文件的描述,所以也许我在那里做错了什么。有人可以帮我看看是什么导致了错误吗?
这是我的头文件:
#import <Foundation/Foundation.h>
@interface MyDownloader : NSURLConnection {
NSURLConnection *connection;
NSURLRequest *request;
NSMutableData *receivedData;
}
-(id) initWithRequest: (NSURLRequest*) req;
@property (nonatomic, retain) NSURLConnection *connection;
@property (nonatomic, retain) NSURLRequest *request;
@property (nonatomic, retain) NSMutableData *receivedData;
@end
这是我的实现(减去 didReceiveResponse、didReceiveData、didFailWithError 和 connectionDidFinishLoading 的实现,这些都是直接从书中取出的):
#import "MyDownloader.h"
@implementation MyDownloader
@synthesize connection;
@synthesize request;
@synthesize receivedData;
-(id) initWithRequest: (NSURLRequest*) req {
self = [super init];
if (self) {
self->request = [req copy];
// Create a connection, but don't start it yet. The connection will be started with a start message.
self->connection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:NO];
self->receivedData = [[NSMutableData alloc] init]; // initialize where the incoming data will be stored
}
return self;
}
- (void)dealloc
{
[receivedData release];
[request release];
[connection release];
[super dealloc];
}
...
@end
最后,这是我对类的使用:
{
...
if (!self.connections) {
self.connections = [NSMutableArray array];
}
NSString *s = @"https://www.myserver.com/myfile.txt";
NSURL *url = [NSURL URLWithString:s];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
MyDownloader *d = [[MyDownloader alloc] initWithRequest:req];
[self.connections addObject:d];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadFinished:) name:@"connectionFinished" object:d];
[d.connection start];
[d release];
...
}
-(void) downloadFinished: (NSNotification *) n
{
MyDownloader *d = [n object];
NSData *data = nil;
if ([n userInfo]) {
NSLog(@"MyDownloader returned an error");
}
else {
data = [d receivedData];
NSLog(@"MyDownloader returned the requested data");
}
[self.connections removeObject:d];
}
【问题讨论】:
-
您是否需要将
MyDownloader子类化为NSURLConnection?首先尝试使其成为NSObject的子类 -
乔,对不起,我没有意识到我应该做些什么来接受答案。我回去接受了所有已回答的答案。向所有之前帮助过我的人道歉,我让你们失望了。
-
巴迪迪,谢谢。这解决了它。就像我说的,这本书没有给出头文件,我错误地认为它需要是 NSURLConnection 的子类,因为该类需要实现: - (void) connection:(NSURLConnection *)connection didReceiveResponse:, - (void )连接:(NSURLConnection *)连接didReceiveData:和-(void)connectionDidFinishLoading:。我想我只是不明白这些方法是如何被“连接”知道的,而不是 NSURLConnection 的子类。
标签: objective-c ios memory-management dealloc