我正在开发基于文档的应用程序,我想使用文档包作为我的文件格式。为此,我需要重写的 NSDocument 方法似乎是
-writeToURL:ofType:error:
.
它有时有效,但仅在某些条件下有效。例如,此代码有效:
- (BOOL)writeToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError
{
NSFileWrapper *wrapper = [[NSFileWrapper alloc] initDirectoryWithFileWrappers:nil];
[wrapper addRegularFileWithContents:[@"please work" dataUsingEncoding:NSUTF8StringEncoding] preferredFilename:@"foobar"];
[wrapper writeToURL:absoluteURL options:NSFileWrapperWritingAtomic originalContentsURL:nil error:outError];
NSDictionary *metadata = [NSDictionary dictionaryWithObject:@"0.1" forKey:@"Version"];
NSURL *mdURL = [NSURL fileURLWithPath:[[absoluteURL path] stringByAppendingPathComponent:@"SiteInfo.plist"]];
[metadata writeToURL:mdURL atomically:YES];
return YES;
}
但是,这段代码没有(它和上面的一样,但是去掉了 NSFileWrapper 位):
- (BOOL)writeToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError
{
NSDictionary *metadata = [NSDictionary dictionaryWithObject:@"0.1" forKey:@"Version"];
NSURL *mdURL = [NSURL fileURLWithPath:[[absoluteURL path] stringByAppendingPathComponent:@"SiteInfo.plist"]];
[metadata writeToURL:mdURL atomically:YES];
return YES;
}
上面的代码将这个神秘的错误放入控制台(“Lithograph”是我的应用程序的名称,“.site”是包扩展名):
NSDocument could not delete the temporary item at file://localhost/private/var/folders/qX/qXL705byGmC9LN8FpiVjgk+++TI/TemporaryItems/(A%20Document%20Being%20Saved%20By%20Lithograph%207)/Untitled%20Site.site. Here's the error:
Error Domain=NSCocoaErrorDomain Code=4 UserInfo=0x10059d160 "“Untitled Site.site” couldn’t be removed."
在我可以将其他文件添加到包之前,我是否必须在原始 URL 中写入一些内容?