Method before main

Discussion in 'Mac Programming' started by perrien, Jul 31, 2010.

  1. perrien macrumors newbie

    Joined:
    Apr 26, 2008
    #1
    I'm writing some very quick, 1 file command line programs (Xcode and Obj-c of course) and am not sure how to include methods. For instance, this is basically what I want to do:

    Code:
    #import <Foundation/Foundation.h>
    
    -(NSString *) returnHello {
    	return @"Hello";
    }
    
    int main (int argc, const char * argv[]) {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
        NSLog(@"%@", [self returnHello]);
    	
        [pool drain];
        return 0;
    }
    The above errors out with "fatal error: method definition not in @implementation context".

    Thanks for any help.

    Ashley
     
  2. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    If you want to write functions that are not part of a class (basically plain C functions) you don't use + or -:
    Code:
    NSString *getHello() {
      return @"Hello, World!";
    }
    
    and you would call it:
    Code:
    NSLog(@"%@",getHello());
    
    Code in Objective-C can exist outside of a class, unlike Java. self has no meaning outside of a class.

    -Lee
     

Share This Page