我已经实现了在Nueburg的编程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];
}
答案 0 :(得分:0)
Baddidi给出了解决方案,我应该将我的类子类化为NSObject,而不是NSURLConnection。