我有一个简单的Mac OS应用程序,它带有默认的MainMenu.xib
。在那里,我有第二个偏好窗口和PreferencesWindowController
。我想让以下测试工作:
@implementation TestPreferencesWindow
- (void)testProtectsUserPasswordByUsingAPasswordField
{
PreferencesWindowController *controller = [[PreferencesWindowController alloc] initWithWindowNibName:@"MainMenu"];
XCTAssertInstanceOf([[controller passwordField] class], NSSecureTextField);
}
@end
问题是[controller passwordField]
没有初始化(因为nib没有加载?)所以它总是返回nil
。
如何告诉笔尖创建所有绑定?
当我致电[controller window]
时,会给出错误,并返回nil
:
Could not connect the action orderFrontStandardAboutPanel: to target of class PreferencesWindowController
为了进行调试,我尝试了以下方法:
NSBundle *bundle = [NSBundle mainBundle];
XCTAssertNotNil(bundle);
NSString *nibPath = [bundle pathForResource:@"MainMenu" ofType:@"nib"];
XCTAssertNotNil(nibPath);
PreferencesWindowController *controller = [[PreferencesWindowController alloc] initWithWindowNibPath:nibPath owner:self];
NSLog(@"%@ %@", [controller window], [controller passwordField]);
然而,它仍会打印(null) (null)
...
要摆脱警告:
NSBundle *bundle = [NSBundle mainBundle];
XCTAssertNotNil(bundle);
NSString *nibPath = [bundle pathForResource:@"MainMenu" ofType:@"nib"];
XCTAssertNotNil(nibPath);
NSApplication *app = [NSApplication sharedApplication];
PreferencesWindowController *controller = [[PreferencesWindowController alloc] initWithWindowNibPath:nibPath owner:app];
NSLog(@"%@ %@", [controller window], [controller passwordField]);
没有更多的警告,但仍打印(null) (null)
..我觉得我越来越近了......
答案 0 :(得分:0)
我得到了解决方案。在.m文件中写下面的方法,并在.h文件中声明public。
MyWindowController.m文件
- (instancetype)initWithWindowNibPath:(NSString *)nibPath {
self = [super initWithWindowNibPath:nibPath owner:self];
if(self)
{
//initialize stuff
}
return self;
}
MyWindowController.h文件
- (instancetype)initWithWindowNibPath:(NSString *)nibPath;
现在编写代码:
NSBundle *bundle = [NSBundle mainBundle];
XCTAssertNotNil(bundle);
NSString *nibPath = [bundle pathForResource:@"MyWindowController" ofType:@"nib"];
XCTAssertNotNil(nibPath);
MyWindowController *controller = [[MyWindowController alloc] initWithWindowNibPath:nibPath];
NSLog(@"%@ %@", [controller window], [controller passwordField]);
这对我来说非常适合。
<强>原因:强> 所有者值未在initWithWindowNibPath方法中正确设置,因此未将类的属性NSOutlet设置为nib的控件。