我正在向文件系统和Dbfile添加一个观察器,但我收到了一个错误,该文件已经打开。请告诉我在哪里关闭我的文件。以下是我的代码:
[filesystem addObserver:self forPathAndChildren:pathDB block:^(DBObserver complete){////observer to folder
DBError *error= nil;
NSLog(@"File(s) %@ changed!",pathDB);
DBFile *file=[filesystem openFile:pathDB error:&error];
[file addObserver:self block:^() { ///observer to file
DBFileStatus *newerStatus = file.newerStatus;
if (newerStatus)
{
if (!newerStatus.cached)
{
NSLog(@"newerStatus.cached == NO; this means the file downloading");
}
else
{
// Update to the newly available version and print it out
[file update:nil];
NSData *fileData = [file readData:nil];
[fileData writeToFile:[[appDelegate.directoryPath stringByAppendingPathComponent:@"Projects"] stringByAppendingFormat:@"/%@",path] atomically:YES];
[file close];
}
}];
}];
请确认,但我猜测错误来自这一行:
DBFile *file=[filesystem openFile:pathDB error:&error];
每次对pathDB
进行更改时都会运行该程序,但您并不总是关闭该文件,因此有时它已经打开了。
我不知道你想用你的代码做什么,因为你在一个路径上设置了一个观察者,然后在该路径的文件上设置了观察者。。。此外,我很确定这段代码不会编译,因为您似乎缺少了一个大括号。
其中一名观察员可能是多余的。也许你想要的只是这个(根本没有路径观测者)?
DBFile *file=[filesystem openFile:pathDB error:&error];
[file addObserver:self block:^() { ///observer to file
DBFileStatus *newerStatus = file.newerStatus;
if (newerStatus)
{
if (!newerStatus.cached)
{
NSLog(@"newerStatus.cached == NO; this means the file downloading");
}
else
{
// Update to the newly available version and print it out
[file update:nil];
NSData *fileData = [file readData:nil];
[fileData writeToFile:[[appDelegate.directoryPath stringByAppendingPathComponent:@"Projects"] stringByAppendingFormat:@"/%@",path] atomically:YES];
[file close];
}
}
}];
我能想到同时拥有两个观察者的唯一原因是,如果你想处理文件不存在的情况。在这种情况下,您拥有的代码可能很接近,但如果您已经有了观察器,则不需要向文件中添加观察器。