我正在写一个代码,它从http连接读取数据并存储在一个字节数组中。 我写了我自己的NSOperation类。代码的参考是NSURLConnection在NSOperation
Concurrent Operations Demystified
我HttpWorker类的声明就像
@interface HttpWorker : NSOperation{
NSString *param;
double requestCode;
BOOL isLive;
long initSleep;
BOOL _isFinished;
BOOL _isExecuting;
NSURL *_url;
NSURLConnection *_connection;
NSData *_data;
}
@property (nonatomic, retain) NSString *param;
@property (nonatomic) double requestCode;
@property (nonatomic) BOOL isLive;
@property (nonatomic) long initSleep;
@property (readonly) BOOL isFinished;
@property (readonly) BOOL isExecuting;
@property (readonly, copy) NSURL *url;
@property (nonatomic, retain) NSURLConnection *httpCon;
@property (readonly, retain) NSData *data;
-(id)initWithUrl:(NSURL *)_url;
-(void) setRequestParameters:(NSString *)parameters iRequestCode:(double)iRequestCode initialSleep:(long)initialSleep;
@end
而且我HttpWorker.m类就像
#import "HttpWorker.h"
#import "Resources.h"
@implementation HttpWorker
@synthesize param;
@synthesize requestCode;
@synthesize isLive;
@synthesize initSleep;
@synthesize isFinished = _isFinished;
@synthesize isExecuting = _isExecuting;
@synthesize url = _url;
@synthesize data = _data;
-(id) initWithUrl: (NSURL *)Url{
self = [super init];
if(self == nil){
return nil;
}
_url = [Url copy];
_isExecuting = NO;
_isFinished = NO;
return self;
}
-(BOOL) isConcurrent{
return YES;
}
-(void) start{
if(![NSThread isMainThread]){
[self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO];
return;
}
[self willChangeValueForKey:@"isExecuting"];
_isExecuting = YES;
[self didChangeValueForKey:@"isExecuting"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:_url];
NSLog(@"Connecting... %@",_url);
_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately: YES];
if(_connection == nil){
NSLog(@"connection is nil");
}
}
-(void) setRequestParameters:(NSString *)parameters iRequestCode:(double)iRequestCode initialSleep:(long)initialSleep {
self.param = parameters;
self.requestCode = iRequestCode;
self.initSleep = initialSleep;
}
/////////////////////////// delegate methods ///////////////////////////////
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"receieved response...");
_data = [[NSData alloc] init];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)incomingData {
NSLog(@"receieved data...");
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
NSLog(@"connection did finish loading...");
}
@end
问题是,当我运行这段代码并将httpworker对象添加到NSOperationQueue中,代码将成功运行并且_connection不为零,但不会执行任何委托方法。任何人都可以帮忙吗?
感谢和问候......
你的假设是不正确的:NSURLConnection的的doc指出:“在下载的连接保持着强劲的参考代表会释放出很强的参考,当连接完成加载,失败,或者被取消。”此外,告诉人们使用第三方框架或库的问题是,第三方通常不再支持他们的解决方案,就像ASIHTTPRequest发生的情况一样。 – 2013-01-29 10:42:37
@elise在这里任何帮助NSURLConnection和NSRunLoop混淆 - http://stackoverflow.com/q/24895099/559017 – Zeeshan 2014-07-23 07:21:07