2011-12-14 74 views
5

我正在研究我的第一個可可/ Objective-C應用程序,所以如果我正在做一些顯然不正確的事情,請耐心等待。我將應用程序設置爲將窗口中NSTextField中的任何內容複製到另一個NSTextField(在本例中爲標籤)。如果用戶沒有在文本框中輸入任何內容,它應該顯示警報,但不是。我的代碼有什麼問題?NSAlert框沒有顯示

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 
} 

此外,是否有由可可UI元素用於方法中的任何引導件(象命名方案)?我使用.NET編程風格。 @end

+0

關於第二個問題,可可命名/編碼指南:HTTP:// developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/ – 2011-12-14 02:30:44

回答

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]; 
+0

它仍然沒有顯示出來。 – airplaneman19 2011-12-14 02:42:45