我正在開發一個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塊。
我如何以安全的方式實現這一點,或者這是一個好主意?
謝謝你的時間。
如果一切已經在GCD內部運行,是否應該應用NSOperation和NSOperationQueue? – Moy
NSOperationQueue使用GCD實現。自從GCD發佈以來,它是GCD的一個高級包裝。您仍然需要將負載分散到其他線程上,以獲得處理數據的流體UI。你可以使用GCD來做,但除非你想要NSOperationQueue不支持的東西,否則更令人頭疼。 – boulette