我的文档包是捆绑包,具有通常的层次结构,因此在保存过程中有四个目录发生了变化:
-
-
目录已更改(My.bundle/目录)
-
-
已更新本地化资源(My.bundle/Contents/Resources/en(lproj先生)
这个方法首先向文档类添加一个可变的字典槽,以保留每个目录的内容。
@interface LMDocument : NSDocument {
@private
NSMutableDictionary * bundleWrappers;
NSMutableDictionary * contentsWrappers;
NSMutableDictionary * resourcesWrappers;
NSMutableDictionary * localizedWrappers;
}
当创建一个新文档时,这些文档以空字典开始。
- (id)init;
{
if ((self = [super init]) != nil) {
bundleWrappers = [[NSMutableDictionary alloc] initWithCapacity:0];
contentsWrappers = [[NSMutableDictionary alloc] initWithCapacity:0];
resourcesWrappers = [[NSMutableDictionary alloc] initWithCapacity:0];
localizedWrappers = [[NSMutableDictionary alloc] initWithCapacity:0];
}
return self;
}
- (BOOL)readFromFileWrapper:(NSFileWrapper *)fileWrapper
ofType:(NSString *)typeName
error:(NSError **)outError;
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
bundleWrappers = [[fileWrapper fileWrappers] mutableCopy];
contentsWrappers = [[[bundleWrappers objectForKey:@"Contents"] fileWrappers] mutableCopy];
resourcesWrappers = [[[contentsWrappers objectForKey:@"Resources"] fileWrappers] mutableCopy];
localizedWrappers = [[[resourcesWrappers objectForKey:@"en.lproj"] fileWrappers] mutableCopy];
NSFileWrapper * infoPlistWrapper = [contentsWrappers objectForKey:@"Info.plist"];
[contentsWrappers removeObjectForKey:@"Info.plist"];
NSMutableDictionary * localizedWrappersCopy = [localizedWrappers mutableCopy];
[localizedWrappers enumerateKeysAndObjectsUsingBlock:^(id key,
id obj,
BOOL * stop)
{
if (mumble) {
[localizedWrappersCopy removeObjectForKey:key];
}
}];
localizedWrappers = localizedWrappersCopy;
[pool drain];
return YES;
}
最后
,保存文档时请使用精心准备的词典。
- (NSFileWrapper *)fileWrapperOfType:(NSString *)typeName
error:(NSError **)outError;
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSFileWrapper * localizedWrapper =
[[NSFileWrapper alloc] initDirectoryWithFileWrappers:localizedWrappers];
[resourcesWrappers setObject:localizedWrapper
forKey:@"en.lproj"];
NSFileWrapper * resourcesWrapper =
[[NSFileWrapper alloc] initDirectoryWithFileWrappers:resourcesWrappers];
[contentsWrappers setObject:resourcesWrapper
forKey:@"Resources"];
NSFileWrapper * contentsWrapper =
[[NSFileWrapper alloc] initDirectoryWithFileWrappers:contentsWrappers];
for (id item in mumble) {
NSString * filename = [item filename];
NSData * data = [item data];
[localizedWrapper addRegularFileWithContents:data
preferredFilename:filename];
}
[contentsWrapper addRegularFileWithContents:[self infoPlistData]
preferredFilename:@"Info.plist"];
[pool drain];
[bundleWrappers setObject:contentsWrapper
forKey:@"Contents"];
NSFileWrapper * bundleWrapper =
[[[NSFileWrapper alloc] initDirectoryWithFileWrappers:bundleWrappers] autorelease];
return bundleWrapper;
}