我正在寫一個代碼,它從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