Multiple Instances of Custom NSView

Ok, so my app is a Menu Extra app. I create NSMenuItems programmatically and add them to the Menu Extra in the Menu Bar. I have a custom NSView in interface builder with some NSTextField’s and an NSImageView. What I want to do is set the same NSView to several NSMenuItems. Then I need to be able to address the NSTextField’s and NSImageView’s of each NSView and fill them with different values (Each instance of the custom NSView will be populated with different values in NSTextField’s and NSImageView’s).

Thanks for any help.

Have a look at NSView’s subviews method.

How exactly would that help me? I know how to set the view of an NSMenuItem (setView:). I can set the same NSView to 5 different NSMenuItem’s but the NSView’s interface objects only appear in one of the NSMenuItem’s so I’m assuming it’s only setting my NSView to the last NSMenuItem.

It sounds like what you really want to do is set the view of several submenus to separate instances of your custom view class, which means an init of sime sort.

not submenus, just menu items.

Right, but I suspect they’re still going to have to have their own instances of the view.

How would I do that and still be able to reference the objects in each view.

As you create each one, you store a reference to it, and then use the subviews method to get a list of the subviews, which you can reference by index.

When you say create each one, do you mean NSMenuItem’s setView:?

No. But a view can only be in one place, or menu item, at a time.

tried this, but the view’s just appear blank without any of the text fields or image views in them:

set firstView to NSView's alloc()'s initWithFrame_(oneView's frame())
		set secondView to NSView's alloc()'s initWithFrame_(oneView's frame())
		set thirdView to NSView's alloc()'s initWithFrame_(oneView's frame())
		set fourthView to NSView's alloc()'s initWithFrame_(oneView's frame())
		set fifthView to NSView's alloc()'s initWithFrame_(oneView's frame())


I think I gave you a bum steer with init.

If you look at Apple’s MenuItemView sample, you’ll see they have separate views. But when they want to attach them to another menu, they make copies by using NSArchiver and NSUnarchiver. And that doesn’t solve the subview problem, so you’d still have to use the subviews method.

I suspect it might just be easier to make a set of identical views.

Figured it out, here it is for anyone who’s interested:

set menuItem to (my NSMenuItem's alloc)'s init
set viewCopyData to NSArchiver's archivedDataWithRootObject_(myView)
set viewCopy to NSUnarchiver's unarchiveObjectWithData_(viewCopyData)
menuItem's setView_(viewCopy)
menuItem's setTarget_(me)
menuItem's setEnabled_(false)
statusMenu's addItem_(menuItem)
menuItem's release()

Is there any better way to reference objects in the view other than:

(item 1 of viewCopy's subviews())'s setStringValue_("string")