【问题标题】:NSAlert box is not showing upNSAlert 框未显示
【发布时间】:2012-01-19 21:32:01
【问题描述】:

我正在开发我的第一个 cocoa/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
}

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

【问题讨论】:

标签: objective-c macos cocoa nsalert


【解决方案1】:

这是你的问题:

if(_textBox1.stringValue != @"")

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

进行这种比较的正确方法是:

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

甚至更好:

if (_textBox1.stringValue.length > 0)

【讨论】:

    【解决方案2】:

    您是否尝试过以模态方式运行警报? beginSheetModalForWindow:

    [msgBox beginSheetModalForWindow:self.window
                       modalDelegate:self 
                      didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:)  
                         contextInfo:nil];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-23
      • 1970-01-01
      • 2017-10-29
      • 2015-07-31
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      相关资源
      最近更新 更多