gpt4 book ai didi

objective-c - cocoa - loadNibNamed :owner:topLevelObjects: from loaded bundle

转载 作者:搜寻专家 更新时间:2023-10-30 20:00:08 25 4
gpt4 key购买 nike

在基于文档的 Cocoa 应用程序中,我使用以下方法从外部包中实例化了几个对象(插件):

- (NSMutableArray *)getPluginsOfType:(Class)type;
{
NSBundle *main = [NSBundle mainBundle];
NSArray *allPlugins = [main pathsForResourcesOfType:@"bundle" inDirectory:@"../PlugIns"];

NSMutableArray *availablePlugins = [NSMutableArray array];

for (NSString *path in allPlugins)
{
NSBundle *pluginBundle = [NSBundle bundleWithPath:path];
[pluginBundle load];
Class principalClass = [pluginBundle principalClass];
[availablePlugins addObject:principalClass];
}
return availablePlugins;
}

在每一个中,一个 nib 文件在初始化时加载,它将 Root View 与我的插件类中的一个属性绑定(bind)。下面是一个最小的插件类定义:

@interface Plugin

@property (strong) IBOutlet NSView *thePluginView;

@end

@implementation Plugin

- (instancetype)init
{
self = [super init];
if (self)
{
[NSBundle loadNibNamed:@"NibName" owner:self];
}
return self;
}

@end

虽然这工作正常,但我想替换上面对 NSBundle 的调用(因为它已被 OS X 10.8+ 弃用),并将其替换为:

[[NSBundle mainBundle] loadNibNamed:@"NibName" owner:self topLevelObjects:nil];

但是,在这种情况下使用 mainBundle 自然无法在我的插件类中设置顶级对象引用,我怀疑是因为 mainBundle 与插件的包无关。

我将如何实现这一目标?有没有办法找到“当前”包(可以说是插件类来自的包)?

谢谢。

最佳答案

我不清楚您到底在问什么 - 不在您的应用程序包中的“加载类”来自哪里,您所说的“加载类”到底是什么意思?

也许以下内容会有所帮助:

loadNibNamed:owner:topLevelObjects: 是一个实例方法并从该实例表示的包中加载。

在您的示例中,您使用的实例是通过 [NSBundle mainBundle] 获取的,因此 nib 是从应用程序主包中加载的。

没有“当前包”的概念,但您可以获得代表其他包的 NSBundle 实例,例如使用 NSBundle 的类方法 bundleWithURL。因此,要从不同的包加载一个 nib,首先创建一个引用该包的 NSURL,然后基于它创建一个 NSBundle,最后加载 nib。

HTH

附录 - 问题更新后

来自已弃用的 +loadNibName:owner: 方法对 owner 的描述:

If the class of this object has an associated bundle, that bundle is searched for the specified nib file; otherwise, this method looks in the main bundle.

这是您在使用 -loadNibNamed:owner:topLevelObjects: 时需要复制的内容。您需要的方法是 NSBundlebundleForClass:,它返回动态加载类的 NSBundle 对象。

因此,在您的 Plugin 类中,您应该能够找到使用 [NSBundle bundleForClass:[self class]] 加载它的包,然后调用 -loadNibNamed:owner:topLevelObjects: 在上面。

关于objective-c - cocoa - loadNibNamed :owner:topLevelObjects: from loaded bundle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21126985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com