我正在研究一个NSDocument
子类。它表示文本编辑器中的文本文件。
我正在尝试使用该NSFilePresenter
协议来响应其他应用程序所做的更改(即,如果用户在 TextEdit 中保存更改而同一文件在此处打开)。
我目前的实现是这样工作的……</p>
我为文件协调器添加了一个属性:
@property (nonatomic) NSFileCoordinator *fileCoordinator;
我懒惰地创建它:
- (NSFileCoordinator *) fileCoordinator {
if (!_fileCoordinator) {
[NSFileCoordinator addFilePresenter:self];
_fileCoordinator = [[NSFileCoordinator alloc] initWithFilePresenter:self];
}
return _fileCoordinator;
}
当presentedItemDidChange
被调用时,我从磁盘重新加载文件并显示它:
- (void)presentedItemDidChange {
[super presentedItemDidChange];
NSLog(@"presentedItemDidChange was called");
if (self.presentedItemURL.isFileURL && self.fileType) {
NSError *coordinatorError = nil;
[self.fileCoordinator coordinateReadingItemAtURL:self.presentedItemURL options:NSFileCoordinatorReadingWithoutChanges error:&coordinatorError byAccessor:^(NSURL *newURL) {
NSError *readError = nil;
[self readFromURL:newURL ofType:self.fileType error:&readError];
if (readError) NSLog(@"%@", readError);
}];
if (coordinatorError) NSLog(@"%@", coordinatorError);
[self reloadString];
}
}
此代码有效:当我在 TextEdit 中保存文件时,更改会出现在我的应用程序中。
但是,一旦我保存了这个文件,presentedItemDidChange
就会重复调用(大约每秒一次)。几分钟后,应用程序由于内存错误而崩溃。没有记录错误;控制台看起来基本上是这样的:
2016-02-17 22:43:46.233 MacDown[66847:2470964] presentedItemDidChange was called
2016-02-17 22:43:51.721 MacDown[66847:2470960] presentedItemDidChange was called
2016-02-17 22:43:52.816 MacDown[66847:2471206] presentedItemDidChange was called
2016-02-17 22:43:53.819 MacDown[66847:2470964] presentedItemDidChange was called
2016-02-17 22:43:54.920 MacDown[66847:2471206] presentedItemDidChange was called
2016-02-17 22:43:56.014 MacDown[66847:2470964] presentedItemDidChange was called
2016-02-17 22:43:57.115 MacDown[66847:2471206] presentedItemDidChange was called
2016-02-17 22:43:58.117 MacDown[66847:2470964] presentedItemDidChange was called
这是我第一次使用这些 API,所以我认为我犯了一个简单的错误。如果重要的话,我正在运行 OS X 10.11.3 和 Xcode 7.2。我究竟做错了什么?