Full Version: Objective C Tutorial
Dream.In.Code > Programming Tutorials > C++ Tutorials
GWatt
This is actually on Objective C tutorial, but the C++ section is the most appropriate.
Anyway, Objective C has the same syntax as C with the addition of Smalltalk like syntax for classes. Objective C classes are usually written in two files. There's a header file which contains the definition and a file which contains the implementation of the class. You can put everything in one file, but that's not the convention. Let's make a person class. . .

NOTE:
To compile this code you will need gcc and GNUStep installed.
If you're running a Mac, you will need XCode. if you're running Windows, install MinGW, and then install GNUStep.
CODE

// Person.h

/*
* Objective C uses #import instead of #include
*/
#import <Foundation/NSObject.h>
#import <Foundation/NSString.h>

/*
* Inheritance in Objective C is shown by a classname
* followed by a colon followed by another classname
* NSObject is the superclass for every Objective C class, either directly or indirectly
*/
@interface Person: NSObject
{
    //Instance data are declared here:
    @private
        NSString* name;
        int age;
}

//Methods are declared here:

/*
* Methods are defined like this
* -(<RETURN_TYPE>) <DESCRIPTION>: (<ARG_TYPE>) <ARG_NAME>
*/
-(Person*) initWithName: (NSString*) n andAge: (int) a;

-(NSString*) name;

-(int) age;

-(NSString*) speak;

@end


CODE

// Person.m

#import "Person.h"

@implementation Person

-(Person*) initWithName: (NSString*) n andAge: (int) a
{
    /*
     * Methods are called with [<CLASS> <METHOD>];
     * init is a method provided by NSObject that provides a default constructor
     */
    self = [super init];
    
    
    /*
     * if the super constructor returned a success, continue initialization
    */
    
    if (self)
    {
        /*
         * release and retain are memory management methods
         * retain increments the count of pointers to a location in memory
         * release does the opposite
         * Once the count is zero the memory is released
         */
        [n retain];
        [name release];
        name = n;
        
        /*
         * age is simply an int, and not a pointer
         * so it's pass-by-value
         */
        age = a;
    }
    
    /*
     * self is analagous to this in C++/Java
     */
    return self;
}

-(NSString*) name
{
    return name;
}

-(int) age
{
    return age;
}

-(NSString*) speak
{
    /*
     * stringWithFormat creates a new string using printf format
     * %@ inserts an NSObject
     * and you don' need to call the init method here, because the
     @ preceding the string constant initializes the string for you
     */
    NSString* result = [ [NSString alloc] initWithFormat:@"Hi.  My name is %@ and my age is %d.",
                        name, age];
    
    return result;
    
}

@end


Now for a driver file

CODE

// main.m

#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSString.h>
#import <stdio.h>
#import "Person.h"

int main(int argc, const char* argv[])
{
    /*
     * alloc reserves memory space for an object
     * NSAutoReleasePool is an automated Garbage collection mechanism
    */
    NSAutoreleasePool* pool = [ [NSAutoreleasePool alloc] init];
    NSString* name = [NSString stringWithString: @"GWatt"];
    Person* gwatt = [ [Person alloc] initWithName: name andAge: 500];
    
    /*
     * printf can't handle NSStrings so we use UTF8String to return a char array
    */
    printf("Name:\t%s\n", [ [gwatt name] UTF8String] );
    printf("Age:\t%d\n", [gwatt age] );
    printf("\n%s\n", [ [gwatt speak] UTF8String] );
    
    [gwatt release];
    
    return 0;
}


We compile this code by opening a terminal and typing
gcc Person.m main.m -o person -framework Foundation -fobjc-exception
and run it by typing
./person
or
person.exe if you're running Windows.

Objective C is not as syntactically close to C as C++ is, but is not a completely new language to learn either. The most practical application of objective c is as an Apple developer since Apple writes their applications using Objective C. It's definitely not as widespread as the .NET languages, but if you want to program on a Mac and want an OOPL that's not Java, Objective C is worth knowing.
GravityGuy
Thanks for the short intro to Objective-C. If Apple software is any indication of the power and flexibility of this language then it's worth a try.

I am generally a number crunching programmer and found the NSNumber class and associated stuff very confusing. I take it that standard C numerics are still available and NSNumber is mainly for interfacing with the GUI, is this right. I'd like to try some simple stuff to see how it would work.

How about a reply with a short program that would read a file of doubles into a container and calculate the average. Are there Foundation classes for handling serious number crunching processes or are we talking standard C arrays and the like.

I see Macs on many desks in Physics and Astronomy prof's offices, so I take it to mean they do well with number-intensive programs - or are they just recompiling Linux programs. Anyway, I have a background in .net but would prefer to work on the Mac.
GWatt
GravityGuy, I would probably just use standard C or C++ IO to read from a text file.
Objective C

NSMutableArray *array = [ [NSMutableArray alloc] init];
NSDecimalNumber *number = [ [NSDecimalNumber alloc] init];
for (int i = 0; i < ARBITRARY_NUMBER; i++)
{
double d;
fscanf(file, "%lf", &d);
[array addObject: [NSDecimalNumber numberWithDouble: d] ];
}
for (int i = 0; i < [array length]; i++)
number = [number decimalNumberByAdding: [array objectAtIndex: i] ];
printf ("average %lf\n", [ [number decimalByDividing: [NSDecimalNumber numberWithInt: [array length] ] doubleValue] );


You could do that entirely with NSStream objects but from what I can tell there is not much ability for 100% objective C to do file handling. It may just be that I'm not looking in the right places.

and finally, for you math profs I would expect that most of the heavy duty math is done with C++ code and the GUI's are written with Cocoa.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2009 Invision Power Services, Inc.