![](/img/trans.png)
[英]iOS: NSFileHandle vs NSOutputStream for large file download
[英]NSFileHandle & Writing Asynch to a file in iOS
我有一种情况,我通过Web服务请求收到字节数据,并希望将其写入我的iOS设备上的文件。 我曾经将所有数据(直到数据末尾)附加到内存变量中,最后使用NSStream
将数据写入我的iOS设备中的文件:
stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent
它适用于小型数据,但问题是,如果我通过Web服务接收数据,它可能是一个很大的块(几个MB),我不想收集所有内存写入文件,到让它高效我想我必须切换到NSFileHandle
,将数据块的小块大小写入同一个文件几次。 现在我的问题是这样做的最佳方法是什么? 我的意思是如何使用NSFileHandle
在BACKGROUND中写入文件? 我使用这样的代码:
- (void) setUpAsynchronousContentSave:(NSData *) data {
NSString *newFilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/MyFile.xml"];
if(![[NSFileManager defaultManager] fileExistsAtPath:newFilePath ]) {
[[NSFileManager defaultManager] createFileAtPath:newFilePath contents:nil attributes:nil];
}
if(!fileHandle_writer) {
fileHandle_writer = [NSFileHandle fileHandleForWritingAtPath:newFilePath];
}
[fileHandle_writer seekToEndOfFile];
[fileHandle_writer writeData:data];
}
但是通过将1-2 Mb的数据大小传递给上面的方法,我是否需要让它在后台运行? 仅供参考我在主线上写作。
也许你可以尝试Grand Central Dispatch 。
我花了一些时间尝试它,下面是我的方式去做。
根据Apple的文档 ,如果我们的程序一次只需执行一个任务,我们应该创建一个“Serial Dispatch Queue”。因此,首先将队列声明为iVar。
dispatch_queue_t queue;
使用在init
或ViewDidLoad
创建一个串行调度队列
if(!queue)
{
queue = dispatch_queue_create("yourOwnQueueName", NULL);
}
发生数据时,请调用您的方法。
- (void) setUpAsynchronousContentSave:(NSData *) data {
NSString *newFilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/MyFile.xml"];
NSFileManager *fileManager = [[NSFileManager alloc] init];
if(![fileManager fileExistsAtPath:newFilePath ]) {
[fileManager createFileAtPath:newFilePath contents:nil attributes:nil];
}
if(!fileHandle_writer) {
self.fileHandle_writer = [NSFileHandle fileHandleForWritingAtPath:newFilePath];
}
dispatch_async( queue ,
^ {
// execute asynchronously
[fileHandle_writer seekToEndOfFile];
[fileHandle_writer writeData:data];
});
}
最后,我们需要在ViewDidUnload
或dealloc
释放队列
if(queue)
{
dispatch_release(queue);
}
我将这些代码与ASIHttp结合起来,并且它可以工作。 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.