Pages

Sunday, July 4, 2010

Simple program to test NSDateFormatter

It is a pleasure to make short and simple program in Xcode 3.2.2. You choose Cocoa Application template and it already contains the application delegate class. The class is very simple, but now I don't need to remember this strange procedure of adding the application controller class and connecting it with the Interface Builder - a year ago I spent hours to get and remember this boring sequence.
One more advantage in Xcode 3.2.2 and programming for Mac OS (not for iPhone) is a small but nice feature - I do not need to declare the instance variables, even if it is the outlet. Instead I simply declare the property.
For this program, that will fulfill the text field with the formatted date and time, the application delegate class looks so:
#import <Cocoa/Cocoa.h>

@interface TextFieldWithDateTimeAppDelegate : NSObject <NSApplicationDelegate>

@property (assign) IBOutlet NSWindow *window;
@property (retain) IBOutlet NSTextField * text;

- (IBAction)populateText:(id) sender;

@end

And here is the implementation:
#import "TextFieldWithDateTimeAppDelegate.h"

@implementation TextFieldWithDateTimeAppDelegate

@synthesize window;
@synthesize text;

- (IBAction)populateText:(id) sender
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDoesRelativeDateFormatting: YES];
[formatter setDateStyle: NSDateFormatterLongStyle];
[formatter setTimeStyle: NSDateFormatterShortStyle];

NSDate *now = [NSDate date];
NSString *formattedDateTime = [formatter stringFromDate: now];

text.stringValue = formattedDateTime;

[formatter release];
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
}

Now, just do not forget to save the changes - Control-S. Few seconds to make the GUI in Interface Builder:

Now "Build and Run":

No comments:

Post a Comment