What's wrong with this Cocoa code?
I'm trying to make a simple Cocoa application using XCode 3.2.3. In interface builder I added NSTextField and NSButton. When I press the button, I want it to clear whatever is in the text field.
I made a new class called AppController.h. This is the contents:
#import <Foundation/Foundation.h>
@interface Ap开发者_开发百科pController : NSObject {
IBOutlet id textView;
}
- (IBAction) clearText: sender;
@end
AppController.m looks like this:
#import "AppController.h"
@implementation AppController
- (IBAction) clearText: sender
{
[textView setString: @" "];
}
@end
I connected the button to clearText and the textbox to textView.
The program compiles without error and runs. But when I press the button, nothing happens. Why is that?
Using id
for an IBOutlet
is a bad practice. Use
IBOutlet NSTextView* textView;
instead.
Please check using the debugger, or putting NSLog(@"foo!");
before [textView setString:@""]
to see if the action method is really called.
Another pitfall is that there are NSTextView
and NSTextField
. These two are different!
The former supports both setString:
and setStringValue:
, while the latter only supports setStringValue:
.
Which object did you use in the interface builder?
精彩评论