I need to download large files from the Internet , and save it to local disk.
At first, i save the data like this:
- (void)saveToLocalFile:(NSData *)data withOffset:(unsigned long long)offset{
NSString* localFile = [self tempLocalFile];
dispatch_async(mFileOperationQueue_, ^{
NSFileHandle* fileHandle = [NSFileHandle fileHandleForWritingAtPath:localFile];
if (fileHandle == nil) {
[data writeToFile:localFile atomically:YES];
return;
}
else {
[fileHandle seekToFileOffset:offset];
[fileHandle writeData:data];
[fileHandle closeFile];
}
});
}
As AFNetworking
use NSOutputstream
to save data to local like this:
NSUInteger length = [data length];
while (YES) {
NSInteger totalNumberOfBytesWritten = 0;
if ([self.outputStream hasSpaceAvailable]) {
const uint8_t *dataBuffer = (uint8_t *)[data bytes];
NSInteger numberOfBytesWritten = 0;
while (totalNumberOfBytesWritten < (NSInteger)length) {
numberOfBytesWritten = [self.outputStream write:&dataBuffer[(NSUInteger)totalNumberOfBytesWritten] maxLength:(length - (NSUInteger)totalNumberOfBytesWritten)];
if (numberOfBytesWritten == -1) {
break;
}
totalNumberOfBytesWritten += numberOfBytesWritten;
}
break;
}
if (self.outputStream.streamError) {
[self.connection cancel];
[self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:self.outputStream.streamError];
return;
}
}
What are the advantages to use NSOutputstream
than NSFileHandle
when writing a file ?
What are the advantages in terms of performance ?