我正在编写一个从http连接读取数据并存储在字节数组中的代码。 我写了自己的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不是nil但是没有执行任何委托方法。有人可以帮忙吗?
谢谢和最诚挚的问候......
答案 0 :(得分:0)
您的连接代表是“self”(=您的NSOperation对象)。我假设当连接想要向委托发送消息时,此对象已经消失。
您的NSOperation没有“主要”实施。因此,线程启动后不会发生任何事情。它将(异步!)触发NSOperation并退出。
结论:我强烈推荐ASIHTTPRequest来完成这类任务。