[英]NSAlert box is not showing up
I'm working on my first ever cocoa/Objective-C application, so please bear with me if I'm doing something obviously incorrect. 我正在研究我的第一个可可/ Objective-C应用程序,所以如果我做的事情明显不正确,请耐心等待。 I have the application set up to copy down whatever is in an NSTextField on the window to another NSTextField (in this case, a label). 我将应用程序设置为将窗口中NSTextField中的任何内容复制到另一个NSTextField(在本例中为标签)。 If the user hasn't entered anything into the text box, it should display an alert, but it isn't. 如果用户未在文本框中输入任何内容,则应显示警报,但不是。 What's wrong with my code? 我的代码出了什么问题?
AppDelegate.m: 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
}
Also, are there any guides to methods used by Cocoa UI elements (like naming schemes)? 此外,是否有任何Cocoa UI元素使用的方法指南(如命名方案)? I'm used the .NET style of GUI programming. 我使用.NET风格的GUI编程。 @end @结束
Here's your problem: 这是你的问题:
if(_textBox1.stringValue != @"")
You're comparing pointer equality, so this expression always returns true
because the string constant @""
will never be the same object as the text field's string object. 您正在比较指针相等性,因此该表达式始终返回true
因为字符串常量@""
永远不会与文本字段的字符串对象相同。
The correct way to do this comparison would be: 进行此比较的正确方法是:
if (![_textBox1.stringValue isEqualToString:@""])
or even better: 甚至更好:
if (_textBox1.stringValue.length > 0)
Have you tried running the alert modally? 您是否尝试过模式运行警报? beginSheetModalForWindow:
[msgBox beginSheetModalForWindow:self.window
modalDelegate:self
didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:)
contextInfo:nil];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.