iOS NSFileHandle使用

 NSFileHandle类是一个针对文件描述符的面向对象封装类。可以使用文件处理对象来访问与文件、sockets、管道pipes和设备相联系的数据。

 对于文件,你可以在文件中读、写、查找。对于套接字socketspipesdevices,可以使用处理对象来异步监视设备和进程数据。

 大部分NSFileHandle类的创建方法都能使文件处理对象获得相关联的文件描述符的所有权。这意味着文件处理对象既负责创建文件描述符也必须负责之后关闭文件,但关闭文件通常发生在文件处理对象销毁时。如果你想使用一个通过你创建的文件描述符对应的文件处理对象,可使用initWithFileDescriptor:initWithFileDescriptor:closeOnDealloc:方法来创建一个File Handle。注意,在调用initWithFileDescriptor:closeOnDealloc:方法创建一个File Handle时, closeOnDealloc:的参数必须为NO

运行回路考虑:

    当你使用一个文件处理对象与套接字进行异步通信时,你必须在有效的运行回路(an active run loop)的线程中初始化相应的操作。尽管在线程的后台异步运行读、写、等待操作,但文件处理使用了一个运行回路源来监视这些操作并且准确的通知到你的代码。因此,你必须在你的应用主线程中,或者在你已经设置的一个运行回路的某个线程,调用这些方法,并且使用它来处理事件。

更多关于设置和使用运行环路的信息,见线程编程指南Threading Programming Guide.

 NSFileHandle的任务有:

     1.获得一个File Handle

         + fileHandleForReadingAtPath:

         + fileHandleForReadingFromURL:error:

         + fileHandleForWritingAtPath:

         + fileHandleForWritingToURL:error:

         + fileHandleForUpdatingAtPath:

         + fileHandleForUpdatingURL:error:

         + fileHandleWithStandardError

         + fileHandleWithStandardInput

         + fileHandleWithStandardOutput

         + fileHandleWithNullDevice

     2.创建一个File Handle

         – initWithFileDescriptor:

         – initWithFileDescriptor:closeOnDealloc:

     3.获得一个文件描述符

         – fileDescriptor

     4.对一个File handle进行读操作

         – availableData

         – readDataToEndOfFile

         – readDataOfLength:

     5.对一个File Handle进行写操作

         – writeData:

     6.使用Blocks设定File Handle读写属性

         readabilityHandler  property使用方法如:@property (copy) void (^readabilityHandler)(NSFileHandle *);//使用Block来异步读取file handle的内容

         writeabilityHandler  property使用方法如:@property (copy) void (^writeabilityHandler)(NSFileHandle *);//使用Block来异步写入到file handle的内容

     7.异步通信

         – acceptConnectionInBackgroundAndNotify

         – acceptConnectionInBackgroundAndNotifyForModes:

         – readInBackgroundAndNotify

         – readInBackgroundAndNotifyForModes:

         – readToEndOfFileInBackgroundAndNotify

         – readToEndOfFileInBackgroundAndNotifyForModes:

         – waitForDataInBackgroundAndNotify

         – waitForDataInBackgroundAndNotifyForModes:

     8.在文件中查找

         – offsetInFile

         – seekToEndOfFile

         – seekToFileOffset:

     9.文件操作

         – closeFile

         – synchronizeFile

         – truncateFileAtOffset:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值