NSAlert框没有显示出来

air*_*n19 5 macos cocoa objective-c nsalert

我正在研究我的第一个可可/ Objective-C应用程序,所以如果我做的事情明显不正确,请耐心等待.我将应用程序设置为将窗口中NSTextField中的任何内容复制到另一个NSTextField(在本例中为标签).如果用户未在文本框中输入任何内容,则应显示警报,但不是.我的代码出了什么问题?

AppDelegate.m:

#import "AppDelegate.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize textBox1 = _textBox1;
@synthesize label1 = _label1;

- (void)dealloc
{
 [super dealloc];
}

-(IBAction)setLabelTxt: (id)sender{

    if(_textBox1.stringValue != @"")
        [_label1 setStringValue: _textBox1.stringValue];
    else{
        NSAlert* msgBox = [[[NSAlert alloc] init] autorelease];
        [msgBox setMessageText: @"You must have text in the text box."];
        [msgBox addButtonWithTitle: @"OK"];
        [msgBox runModal];
        }
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
}
Run Code Online (Sandbox Code Playgroud)

此外,是否有任何Cocoa UI元素使用的方法指南(如命名方案)?我使用.NET风格的GUI编程.@结束

Fra*_*rew 10

这是你的问题:

if(_textBox1.stringValue != @"")

您正在比较指针相等性,因此该表达式始终返回,true因为字符串常量@""永远不会与文本字段的字符串对象相同.

进行此比较的正确方法是:

if (![_textBox1.stringValue isEqualToString:@""])

甚至更好:

if (_textBox1.stringValue.length > 0)