Reputation: 89
I'm trying to load a view from a xib file in my cocoa application (I use storyboards).
So, I have FirstView.xib and some custom view in storyboard's ViewController named "_contentView". I do the following:
NSArray *nibObjects;
[[NSBundle mainBundle] loadNibNamed:@"FirstView" owner:self topLevelObjects:&nibObjects];
[_contentView addSubview: nibObjects[1]];
..and it works, but sometimes I get the following error:
-[NSApplication window]: unrecognized selector sent to instance 0xXXXXXXXXXXXX
Failed to set (contentViewController) user defined inspected property on (NSWindow): -[NSApplication window]: unrecognized selector sent to instance 0xXXXXXXXXXXXX
What am I doing wrong and how can this be fixed?
Upvotes: 0
Views: 1378
Reputation: 8793
Don't look at the nibObjects array. That array is only there to hold on to all top-level objects in the nib. I.e. So you can just release it to have all of them go away.
Instead, define an outlet in your class (the class of the object you pass as the owner) and connect it to the desired view. Then you can just load the nib and use the view in the outlet. That is what outlets are for.
Update: If you have a whole list or want to otherwise load several copies of the same XIB, create e.g. a separate MYListItemViewController for each XIB, and have that do the loading, then have your current controller just create MYListItemViewControllers and keep an array of those, instead of directly loading them.
That's how XIBs were designed to work. It's not a good idea to load several XIBs on the same owner, You'll get multiple awakeFromNib messages, for one, and nobody expects it, so someone might add an outlet and then it gets overwritten with each load.
Upvotes: 1
Reputation: 89
So, thanks to @Willeke. The solution is:
NSArray *nibObjects = [[NSArray alloc] init];
[[NSBundle bundleForClass:[self class]] loadNibNamed:subViewName owner:self topLevelObjects:&nibObjects];
if ([nibObjects[1] isKindOfClass:[NSView class]]){
[_customView setSubviews:[NSArray array]];
[_customView addSubview: nibObjects[1]];
}
else {
[_customView setSubviews:[NSArray array]];
[_customView addSubview: nibObjects[0]];
}
Upvotes: 0