2013-04-15 4 views
1

모든 작업을 실행하지. NSOperationQueue 내가 동시 다운로드를 수행하고 핵심 데이터에 삽입 할 NSOperationQueue를 사용하고

다음

나는 큐가 실행되지 않고,

if(nil==queue) 
{ 
    queue=[[NSOperationQueue alloc]init]; 
    [queue setMaxConcurrentOperationCount:5]; 
} 
for (FileDetailsEntity *entity in array) 
{ 
    InoFileDownloader *fileDownloader=[[InoFileDownloader alloc]initWithFileDetailsEntity:entity andDelegate:self]; 
    [queue addOperation:fileDownloader]; 
} 


//InoFiledownloader.m file 

- (void)mergeChanges:(NSNotification *)notification 
{ 
    appDelegate=(InoAppDelegate*)[[UIApplication sharedApplication]delegate]; 
    NSManagedObjectContext *mainContext = [appDelegate managedObjectContext]; 

// Merge changes into the main context on the main thread 
[mainContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) 
           withObject:notification 
          waitUntilDone:YES]; 
} 


-(void)start 
{ 
    @autoreleasepool { 


    [self willChangeValueForKey:@"isExecuting"]; 
    self.isExecuting = YES; 
    [self didChangeValueForKey:@"isExecuting"]; 

    appDelegate=(InoAppDelegate*)[[UIApplication sharedApplication]delegate]; 

    NSManagedObjectContext *ctx = [[NSManagedObjectContext alloc] init]; 
    [ctx setUndoManager:nil]; 
    [ctx setPersistentStoreCoordinator: [appDelegate persistentStoreCoordinator]]; 


    // Register context with the notification center 
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 
    [nc addObserver:self 
      selector:@selector(mergeChanges:) 
       name:NSManagedObjectContextDidSaveNotification 
      object:ctx]; 

    NSDictionary *taskID=[[NSDictionary alloc]initWithObjectsAndKeys:fileDetaislsEntity.fileId,@"fileId",nil]; 

    NSArray *arry=[[NSArray alloc]initWithObjects:taskID, nil]; 

    NSMutableDictionary *jsonRequest=[NSMutableDictionary new]; 

    [jsonRequest setValue:arry forKey:@"fileId"]; 

    jsonWriter = [[SBJsonWriter alloc] init]; 

    if(self.isCancelled) 
     return; 

    NSString *jsonString = [jsonWriter stringWithObject:jsonRequest]; 

    NSData *postData = [jsonString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; 

    if(self.isCancelled) 
     return; 


    NSURL *url = [NSURL URLWithString:@"http://192.168.4.247:8080/InnoApps/mobjobs/post/imageDownload"]; 

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
    [request setURL:url]; 
    [request setHTTPMethod:@"POST"]; 
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 

    if(self.isCancelled) 
     return; 

    [request setHTTPBody:postData]; 
    NSHTTPURLResponse* response; 
    NSError* error = nil; 

    // NSLog(@"File started to download for the file id %@",entity.fileId); 

    if(self.isCancelled) 
     return; 

    //Capturing server response 
    NSLog(@"started to download for file id--%@",fileDetaislsEntity.fileId); 
    NSData* result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
    NSLog(@"finished downloading data for file id--%@",fileDetaislsEntity.fileId); 
    // if(request) 
    //  NSLog(@"File downloaded for the file id %@",entity.fileId); 

    if(self.isCancelled) 
     return; 

    SBJSON *jsonParser=[SBJSON new]; 

    NSString *jsonStr=[[NSString alloc]initWithData:result encoding:NSUTF8StringEncoding]; 


    // if(response.statusCode!=0) 
    NSDictionary *resultDic; 

    if([response statusCode]!=0) 
    { 
     resultDic= [jsonParser objectWithString:jsonStr]; 
    } 
    else 
    { 
     resultDic=nil; 
    } 

    // NSLog(@"resultDic---%@",resultDic); 

    NSMutableDictionary *imageDetails= [[resultDic objectForKey:@"image"] objectAtIndex:0]; 
    NSString *imageStr=[imageDetails objectForKey:@"imageBlob"]; 


    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
    NSEntityDescription *entity = [NSEntityDescription 
            entityForName:@"FileDetailsEntity" inManagedObjectContext:ctx]; 

    [fetchRequest setEntity:entity]; 
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"taskId = %@ AND fileId=%@",fileDetaislsEntity.taskId,fileDetaislsEntity.fileId]; 

    [fetchRequest setPredicate:predicate]; 

    NSError *errorTmp=nil; 
    NSArray *fileDetailsArray= [ctx executeFetchRequest:fetchRequest error:&error]; 

    if(errorTmp) 
     NSLog(@"error in fetching filedetails array----%@",[errorTmp localizedDescription]); 
    for(FileDetailsEntity *entity in fileDetailsArray) 
    { 
     [entity setFileData:[imageStr dataUsingEncoding:NSUTF8StringEncoding]]; 
    } 




    if(self.isCancelled) 
     return; 

    NSError *errorForDataSaving; 

    if(![ctx save:&errorForDataSaving]) 
     NSLog(@"failed to save data after downloading image ---%@",[error localizedDescription]); 

    NSLog(@"data saved in db for file id--%@",fileDetaislsEntity.fileId); 

    if(self.isCancelled) 
     return; 


    [self willChangeValueForKey:@"isFinished"]; 
    [self willChangeValueForKey:@"isExecuting"]; 
    isExecuting = NO; 
    isFinished = YES; 
    [self didChangeValueForKey:@"isExecuting"]; 
    [self didChangeValueForKey:@"isFinished"]; 

    [(NSObject*)self.delegate performSelectorOnMainThread:@selector(didFinishDownloadingFileWithFileId:) withObject:fileDetaislsEntity.fileId waitUntilDone:NO]; 



} 

} 


-(BOOL)isConcurrent { return YES; } 

-(BOOL)isExecuting { return isExecuting; } 

-(BOOL)isFinished { return isFinished; } 

-(BOOL)isCancelled { return cancelled; } 

만이 그 후 15 또는 20 최대 작업을 실행 사용하고, 코드입니다. 누군가 말해 줄 수 있어요. 뭐가 잘못 됐어. 또한

if(nil==queue) 
{ 
    queue=[[NSOperationQueue alloc]init]; 
    [queue setMaxConcurrentOperationCount:5]; 
} 

[queue setSuspended:YES]; 

for (FileDetailsEntity *entity in array) 
{ 
    InoFileDownloader *fileDownloader=[[InoFileDownloader alloc]initWithFileDetailsEntity:entity andDelegate:self]; 
    [queue addOperation:fileDownloader]; 
} 

[queue setSuspended:NO]; 

을 병합에 :

+0

사용'(큐 == 전무)의 경우' – filou

답변

0

문제는 잘 수 있습니다. 이것은 거의 항상 (무슨 일이 일어나고 정확히 같은 소리) 완전한 정지에 코드를 가져올 수있는, 무엇보다도 의미 그것 때문에 블록, 나쁜 생각이다. 그들이 두려워 또는 비동기 즉, 제대로있는 NSURLConnection을 사용하는 방법을 모르기 때문에

사람들은 일반적으로 NSURLConnection sendSynchronousRequest를 사용합니다. 그러나 제대로 사용하는 것이 어렵지 않으며, 할 가치가 있습니다.

+0

안녕 매트, 당신의 대답을 주셔서 대단히 감사합니다. 동기 요청을 비동기로 변경하면 내 문제가 해결됩니다. – Karthick

2

당신은

이 함께 시도 ... 당신이 작업 풀 추가 finsh 그 후 큐를 다시 시작 스와 전에 큐를 일시 중단 작업을 추가해야한다 변경이 같은 FALSE로 플래그 waitUntillDone에 방법 변경 : 당신이 NSURLConnection sendSynchronousRequest을 사용하고 있는지

[mainContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) 
          withObject:notification 
         waitUntilDone:FALSE];