Search code examples
objective-cmacoscocoansalert

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. 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). 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:

#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)? I'm used the .NET style of GUI programming. @end


Solution

  • 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.

    The correct way to do this comparison would be:

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

    or even better:

    if (_textBox1.stringValue.length > 0)