我正在用可可编程的应用程序在运行时安装其他NSBundles。但是我无法从中获取任何资源。到目前为止的代码是:
-(void)load {
NSString *appSupportSubpath = [[NSBundle mainBundle] builtInPlugInsPath];
NSArray *bundlePaths = [NSBundle pathsForResourcesOfType:@"bundle" inDirectory:appSupportSubpath];
NSEnumerator *searchPathEnum;
NSString *currPath;
searchPathEnum = [bundlePaths objectEnumerator];
NSMutableArray *classes = [[NSMutableArray alloc] init];
while(currPath = [searchPathEnum nextObject])
{
NSBundle *pluginBundle = [NSBundle bundleWithPath:currPath];
if(![pluginBundle isLoaded]) {
[pluginBundle load];
}
Class principalClass = [pluginBundle principalClass];
if ([principalClass isSubclassOfClass:[AddOn class]]) {
[classes addObject:principalClass];
}
}
addOnLibrary = classes;
}
-(NSArray *)infos {
NSMutableArray *infos = [[NSMutableArray alloc] init];
NSEnumerator *enumerator;
Class theClass;
enumerator = [addOnLibrary objectEnumerator];
while(theClass = [enumerator nextObject])
{
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setValue:[theClass patchname] forKey:@"name"];
[dictionary setValue:NSStringFromClass(theClass) forKey:@"classname"];
[dictionary setValue:[theClass icon] forKey:@"icon"];
//Here icon is nil for AddOns added during runtime
[infos addObject:dictionary];
}
return infos;
}
//the addon-icon method
+(NSImage *)icon {
NSBundle *myBundle = [NSBundle bundleForClass:[self class]];
return [[NSImage alloc] initWithContentsOfFile:[myBundle pathForImageResource:@"icon.png"]];
}
为什么在程序启动时可用的插件具有图标,并且在运行时安装的插件图标返回nil?
谢谢
最佳答案
-[NSBundle pathsForResourcesOfType:inDirectory:]
不采用任意目录名称。它采用包的Resources目录的子目录的名称。
如果您要查找插件,则自己枚举[[NSBundle mainBundle] builtInPlugInsPath]
的内容。
我认为基本问题是查找和加载插件的每一步都失败了,但是您没有检查任何假设,因此您没有意识到这一点。最后,当您去获取图标时,您得到的捆绑包nil
却没有引起注意。当然,当您要求它提供图标时,您是在发送nil
消息并取回nil
。
关于cocoa - 运行时加载的NSBundle不提供资源路径,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10861349/