文件句柄NSFileHandle

在做网络下载的时候,如果直接下载文件存储到内存(沙盒).可能因内存的突然增大而导致程序crash.

在这种情况下我们可以使用文件句柄(NSFileHandle).来解决这个问题.

在苹果官方文档里面最重要的一句话就是:

When using a file handle object to communicate asynchronously with a socket, you must initiate the corresponding operations from a thread with an active run loop. Although the read, accept, and wait operations themselves are performed asynchronously on background threads, the file handle uses a run loop source to monitor the operations and notify your code appropriately. Therefore, you must call those methods from your application’s main thread or from any thread where you have configured a run loop and are using it to process events.

这句话告诉我们如果是在子线程(基本上都是在子线程上处理.主线程操作句柄会带来UI的卡顿)操作文件句柄,那么需要有一个存在的运行循环.

我们知道,不管是使用什么原生的多线程技术.创建的子线程是没有runloop循环的.需要我们手动来创建(主线程从程序一启动就自动创建了一个RunLoop循环).


NSFileHandle的原理在我看来就是在网络数据和本地内存(缓存).之间架设了一个桥梁.让每次从网络(或者是其他什么地方).下来的数据,一点点的存进了内存.因为是一段一段的写入,就不会造成一次性写入的大量内存占用.

我们可以使用NSFileHandle的类方法+ fileHandleForReadingAtPath:来初始化一个NSFileHandle类的对象.如果给了path之后返回的是nil代表.没这个文件.我们然后就直接往这个路径里面写入数据.然后如果不是nil.我们就需要使用NSFileHandle的对象方法-seekToEndOfFile来使文件句柄的操作指针移动到文件末尾.然后再追加数据.

并且.每次写入之后都不要忘记使用对象方法-closeFile来关闭句柄.如果关闭之后还尝试读取文件句柄.那么就会引起异常


版权声明:本文为qq_18683985原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。