Strings
There are four files:
say.h:
#ifndef _Say_H_
#define _Say_H_
#include <Foundation/NSObject.h>
@interface Say: NSObject
{
}
- (void) sayHello;
- (void) sayHelloTo: (NSString *)name;
@end
#endif /* _Say_H_ */
say.m:
#include "say.h"
#include <Foundation/Foundation.h>
@implementation Say
- (void) sayHello
{
NSLog(@"Hello World");
}
- (void) sayHelloTo: (NSString *)name
{
NSLog(@"Hello World, %@", name);
}
@end
main.m:
#include "say.h"
#include <Foundation/Foundation.h>
int main (void)
{
id speaker;
NSString *name = @"GNUstep !";
NSAutoreleasePool *pool;
pool = [NSAutoreleasePool new];
speaker = [[Say alloc] init];
[speaker sayHello];
[speaker sayHelloTo:name];
RELEASE(speaker);
RELEASE(pool);
}
GNUmakefile:
include $(GNUSTEP_MAKEFILES)/common.make
APP_NAME = HelloWorld
HelloWorld_HEADERS = say.h
HelloWorld_OBJC_FILES = main.m say.m
HelloWorld_RESOURCE_FILES =
include $(GNUSTEP_MAKEFILES)/application.make
Again, use 'make' and 'openapp' to compile and run this application. This example is self-explained. There are several things worthy to metion.
The class "Say" inherits from "NSObject", which is the root class of GNUstep. Always inherit from NSObject if you don't know which class to use. NSObject contains many fundamental methods which you won't want to implement by yourself.
NSLog() is used instead of printf() because it is as easy as printf(). And most importantly, NSLog() accept the %@ symbol, which represents an object. That means you can print objects in NSLog(). Very handy for debug.
NSString is one of the most used classes in GNUstep. You can use @"..." to create a NSString. There are many useful methods in NSString to manipulate strings and pathes. Check these articles: String in Cocoa: Part I, Part II
NSAutoreleasePool is the place for autoreleased instances. In this example, it is not much useful, but I think it is a good habit to use it. When the application should end, remember to release it. Methods -alloc and -init is the standard method to create an instance. Method -new is a shortcut if there is no messages for -init.