NSAlert提示框没有显示出来。

5

我正在开发我的第一个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编程。

对于你的第二个问题,可以参考Cocoa命名/编码指南: http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/ - jscs
2个回答

10

以下是您的问题:

if(_textBox1.stringValue != @"")

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

正确比较方式应该是:

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

甚至更好的方式:

if (_textBox1.stringValue.length > 0)


0

你尝试过以模态方式运行警报吗?beginSheetModalForWindow:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接