2013-08-16 33 views
0

我正在开发一个iPhone应用程序,我对objective-c比较陌生,所以我希望有人能提供一些线索。如何安全地同时运行多个任务?

我在做什么是块读取文件,并编码为base64的大块,一切工作正常,问题是,在这一行NSString * str = [data base64EncodedString];它需要一点时间,因为即时编码256KB的块,没有问题,一个文件的问题是,我编码的图像文件,所以想象我编码10个图像它会很多每个图像的块,所以过程可以缓慢。

这是过程:
*获取文件。
*读取文件的256KB的chunck。
*将chunck编码为base64。
*保存编码的chunck并重复,直到没有更多的字节从文件中读取。

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; 
[library assetForURL:referenceURL resultBlock:^(ALAsset *asset) 
{ 

    NSUInteger chunkSize =262144; 
    uint8_t *buffer = calloc(chunkSize, sizeof(*buffer)); 
    ALAssetRepresentation *rep = [asset defaultRepresentation]; 
    NSUInteger length = [rep size]; 

    self.requestsToServer=[[NSMutableArray alloc]init]; 
    NSUInteger offset = 0; 
    do { 
     NSUInteger bytesCopied = [rep getBytes:buffer fromOffset:offset length:chunkSize error:nil]; 
     offset += bytesCopied; 

     NSData *data = [[NSData alloc] initWithBytes:buffer length:bytesCopied]; 

     NSString *str = [data base64EncodedString]; 

     //After this I add the str in a NSMutableURLRequest and I store the request 
      //in a NSMutableArray for later use. 

     } while (offset < length); 
    free(buffer); 
    buffer = NULL; 
} 
     failureBlock:^(NSError *error) 
{ 

}]; 

我要开始另一个线程,所以我可以在编码的相同常和chuncks知道什么时候在流程结束,这样,当编码一个chunck我可以在同一时间被encodign另外3个或4块。

我如何以安全的方式实现这一点,或者这是一个好主意?

谢谢你的时间。

回答

1

看看NSOperation和NSOperationQueue。

http://developer.apple.com/library/ios/DOCUMENTATION/Cocoa/Reference/NSOperationQueue_class/Reference/Reference.html

简单地创建每块一个的NSOperation,并通过他们,他们需要编码并预约块。

您可以告诉队列可以同时运行多少个操作。

+0

如果一切已经在GCD内部运行,是否应该应用NSOperation和NSOperationQueue? – Moy

+0

NSOperationQueue使用GCD实现。自从GCD发布以来,它是GCD的一个高级包装。您仍然需要将负载分散到其他线程上,以获得处理数据的流体UI。你可以使用GCD来做,但除非你想要NSOperationQueue不支持的东西,否则更令人头疼。 – boulette

相关问题