My solution


#1

The solution to this one came pretty easy to me.

My AppDelegate.h file

[code]#import <Cocoa/Cocoa.h>

@interface AppDelegate : NSObject

@property (assign) IBOutlet NSWindow *window;
@property (weak) IBOutlet NSTextField *textField;
@property (weak) IBOutlet NSTextField *textLabel;

  • (IBAction)countCharacters:(id)sender;
    @end[/code]

My AppDelegate.m file

[code]#import “AppDelegate.h”

@implementation AppDelegate

@synthesize window = _window;
@synthesize textField = _textField;
@synthesize textLabel = _textLabel;

  • (void)applicationDidFinishLaunching:(NSNotification *)aNotification
    {
    // Insert code here to initialize your application
    }

  • (IBAction)countCharacters:(id)sender {
    // Get the string
    NSString *theString = [_textField stringValue];

    // Count the characters and compose the string
    NSInteger count = [theString length];
    NSString *stringToDisplay = [NSString stringWithFormat:@""%@" has %lu characters", theString, count];

    // Display the string and the count
    [_textLabel setStringValue:stringToDisplay];

    // Clear the textField
    [_textField setStringValue:(@"")];

}
@end[/code]


#2

Thanks for posting.


#3

Here’s another take using a controller class.

CountCharacterController.h

#import <Foundation/Foundation.h>

@interface CountCharacterController : NSObject {
    IBOutlet NSTextField *inputText;
    IBOutlet NSTextField *outputText;
}

- (IBAction)countCharacter:(id)sender;

@end

CountCharacterController.m

#import "CountCharacterController.h"

@implementation CountCharacterController

- (IBAction)countCharacter:(id)sender
{
    NSInteger countCharacters = 0;
    NSString *textToProcess = [[NSString alloc] initWithString:[inputText stringValue]];
    countCharacters = [textToProcess length];
    
    NSString *displayText = [[NSString alloc] initWithFormat:@"'%@' has %d characters.", textToProcess, countCharacters];
    [outputText setStringValue:displayText];
}

- (void)awakeFromNib
{
    [outputText setStringValue:@"???"];
}

@end