KVO download file example code
#import <Foundation/Foundation.h>
@interface MyOperation : NSOperation{
NSURLRequest *_request;
NSURLConnection *_connection;
NSMutableData *_data;
BOOL isFinished;
NSURL *_url;
}
-(id)initWithURLString:(NSString *)url;
-(NSData *)data;
-(NSURL *)url;
@end;
#import <Foundation/Foundation.h>
#import "MyOperation.h"
@implementation MyOperation
-(void)dealloc{
[_request release],_request=nil;
[_data release],_data=nil;
[_connection release],_connection=nil;
[_url release], _url = nil;
[super dealloc];
}
-(NSData *)data{
return _data;
}
-(NSURL *)url{
return _url;
}
-(id)initWithURLString:(NSString *)aURL{
self = [super init];
if (self){
NSURL *bURL = [NSURL URLWithString:aURL];
_request = [[NSURLRequest alloc] initWithURL:bURL];
_data = [[NSMutableData alloc] init];
_url = bURL;
}
return self;
}
- (BOOL)isFinished{
return isFinished;
}
// , .
- (BOOL) isConcurrent{
return YES;// yes ,
}
/* start 。Start NSOperation , ,
* , NSOperation ( ), ,
* ( delegate ) 。 start
*
*
*/
-(void) start{
if (![self isCancelled]){
NSLog(@"start operation");
_connection = [[NSURLConnection connectionWithRequest:_request delegate:self] retain];
// , ,
// connection delegate ,
while(_connection != nil){
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
}
//[self setValue:[NSNumber numberWithBool:YES] forKey:@"isFinished"];
}
+ (BOOL) automaticallyNotifiesObserversForKey: (NSString*)aKey{
NSLog(@"Called automaticallyNotifiesObserversForKey function.");//KVO
if ([aKey isEqualToString:@"isFinished"]){
return YES;
}
return [super automaticallyNotifiesObserversForKey:aKey];
}
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data {
NSLog(@"connection:");
[_data appendData:data];
}
// HTTP
- (void)connectionDidFinishLoading:(NSURLConnection*)connection {
[_connection release],_connection=nil;
[self setValue:[NSNumber numberWithBool:YES] forKey:@"isFinished"];
}
-(void)connection: (NSURLConnection *) connection didFailWithError: (NSError *) error{
NSLog(@"connection error");
[self setValue:[NSNumber numberWithBool:YES] forKey:@"isFinished"];
}
@end;
CallOperation
#import <Foundation/Foundation.h>
#import "MyOperation.h"
@interface CallOperation : NSObject{
}
-(void)call;
@end;
#import <Foundation/Foundation.h>
#import "MyOperation.h"
#import "CallOperation.h"
@implementation CallOperation
-(void)call{
}
- (void) observeValueForKeyPath: (NSString*)aPath
ofObject: (id)anObject
change: (NSDictionary*)aChange
context: (void*)aContext{
if ([aPath isEqualToString:@"isFinished"]){
BOOL isFinished=[[aChange objectForKey:NSKeyValueChangeNewKey] intValue];
if (isFinished){
NSLog(@"call observeValueForKeyPath function.");
MyOperation *opr = (MyOperation *)aContext;
NSURL *url = [opr url];
NSString *fileName = [[url absoluteString] lastPathComponent];
if (!fileName){
fileName = @"index.html";
}
//NSLog(@"data is: %@", [opr data]);
[[opr data] writeToFile:fileName atomically:YES];
// kvo
//[opr removeObserver:self forKeyPath:@"isFinished"];
//NSLog(@"removeObserver:forKeyPath");
}
}else{
[super observeValueForKeyPath:aPath
ofObject:anObject
change:aChange
context:aContext];
}
}
@end;
main
#import <Foundation/Foundation.h>
#import "MyOperation.h"
#import "CallOperation.h"
int main (int argc, const char *argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
CallOperation *call = [[CallOperation alloc] init];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
MyOperation *operation1 = [[MyOperation alloc] initWithURLString:@"http://www.eet-china.com/"];
[operation1 addObserver:call
forKeyPath:@"isFinished"
options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
context:operation1];
[queue addOperation:operation1];
MyOperation *operation2 = [[MyOperation alloc] initWithURLString:@"http://www.eet-china.com/ART_8800646672_617693_NT_f0b705ea.HTM"];
[operation2 addObserver:call
forKeyPath:@"isFinished"
options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
context:operation2];
[queue addOperation:operation2];
[NSThread sleepForTimeInterval:80];// 80
[operation1 release];
[operation2 release];
[call release];
[queue release];
[pool drain];
return 0;
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.