简体   繁体   English

如何使NSFilehandle在Objective C中同时删除和写入数据

[英]How to make NSFilehandle to delete and write data concurrently in Objective c

I have written 2 methods: 我写了两种方法:

  1. WriteToLogFile WriteToLogFile

  2. DeleteLogFile DeleteLogFile

and I am using NSFileHandle for this 我为此使用NSFileHandle

My Code is written as: 我的代码写为:

- (void)WriteToLogFile:(NSString *)string {

 dispatch_async(logQueue ,^ {
        if (nil == fileHandle) {
            // log file not opened
            NSLog(@"LogFile not opened");
            return;
        }
        [fileHandle seekToEndOfFile];
        [fileHandle writeData:[string dataUsingEncoding:NSUTF8StringEncoding]];
      });
    }

And other function to delete as: 等功能删除为:

-(void) deleteLogDataFromFile
{
    NSString *logFilePath = [self getLogFilePath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:logFilePath])
    {
    [[NSFileManager defaultManager] createFileAtPath:logFilePath contents:[NSData data] attributes:nil];
    fileHandle = [NSFileHandle fileHandleForWritingAtPath:logFilePath];
    }
}

Now I am calling these 2 methods from a loop to check if it crashes at some point where it fileHandle will try to Write to file and will found no such file exist 现在,我从循环中调用这两个方法,以检查它是否在fileHandle的某个点崩溃,它将尝试写入文件,并且发现不存在此类文件

for (int i = 0; i<1000; i++) {
    [self WriteToLogFile:@"Hello"];
    [self DeleteLogs];
}

And Xcode throws me error b/w loop is running 和Xcode抛出错误错误黑白循环正在运行

Terminating app due to uncaught exception 'NSFileHandleOperationException', reason: '*** -[NSConcreteFileHandle writeData:]: Bad file descriptor' 由于未捕获的异常“ NSFileHandleOperationException”而终止应用程序,原因:“ ***-[NSConcreteFileHandle writeData:]:错误的文件描述符”

So I need to know how should I make my Write to file Or Delete to file work together , I know I should do some locking on fileHandle. 所以我需要知道如何使我的写入文件或删除文件协同工作,我知道我应该对fileHandle进行一些锁定。 Can anyone tell what should be done in order to fix this issue? 谁能说出解决该问题的方法?

A simple dispatch_async(logQueue ,^ {...}); 一个简单的dispatch_async(logQueue ,^ {...}); in deleteLogDataFromFile method should do the trick. 在deleteLogDataFromFile方法中应该可以解决问题。 (assuming logQueue sa serial dispatch queue). (假设logQueue为串行调度队列)。

For additional safety, consider making fileHandle a property in the class. 为了提高安全性,请考虑将fileHandle设置为类中的一个属性。 Then override the getter, use 然后覆盖吸气剂,使用

@ synchronized(_fileHandle){
    return _fileHandle
}

And finally, use self.fileHandle in WriteToLogFile method. 最后,在WriteToLogFile方法中使用self.fileHandle。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM