开发者

Programmatically creating new windows and accessing window objects in Cocoa

I'm having an issue with creating new windows in Cocoa. Hypothetically speaking, let's say I have "WindowA" and has a button called "myButton". When you click on "myButton", it runs this code in the following class file:

 -(void)openFile2:(id)sender
{
    myNextWindow = [[TestWindowControll开发者_C百科er alloc] initWithWindowNibName:@"MainMenu"];
    NSString *testString = @"foo";

    [myNextWindow showWindow:self];
    [myNextWindow setButtonText:testString];
}

The code in a nutshell makes a duplicate "WindowA" and shows it. As you can see, this code also runs a method called 'setButtonText', which is this:

- (void)setButtonText:(NSString *)passedText
{
    [myButton setTitle:passedText];
}

The problem is that when I call this method locally, in the original window - the button text changes (e.g., [self setButtonText:testString]) it works. However, it does not work in the newly created window (e.g., [myNextWindow setButtonText:testString];)

When I debug the newly created window, step by step, the 'myButton' value it gives is 0x0. Do I have to manually assign controllers/delegates to the new window? I think the 'myButton' in the code isn't associated to the 'myButton' in the newly created window.

How would I fix this problem?


The first problem is that you are loading the MainMenu NIB/XIB repeatedly. That will do Very Bad Things -- the MainMenu should only be loaded once at application startup.

You want to break out any UI that needs to be loaded repeatedly into a separate NIB/XIB file (the same way a document based application has a MainMenu.xib and Document.xib files).

To properly do this, you need to understand the concept of "File's Owner" and how to leverage it properly. Note that there is also overlap with window controllers and understanding those, if you want to use them, will be helpful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜