1

I am working on a simple Objective-C tutorials for some friends and it came to a very simple question I could not answer. In a Foundation Tool project, why is main a method? At least its is called "main-method" in all the books I read.

Let me tell you about the details ... I made a small program where a NSMutableArray is sorted with a function. I put the function before main and it all works fine. My problem is how to explain a beginner why main is a method while the code to sort the array is a function. It's hard to see any difference.

We all know methods always belong to classes while functions do not but in my project I have no classes only the main.m. A C++ guy like me I expected main to be static but it is not.

So the question is "Why is main a method and not a function?" Or is it not? Or is it something completely different?

TalkingCode
  • 13,407
  • 27
  • 102
  • 147

3 Answers3

3

Ah.... well you're mixing C and Objective-C syntax I believe.

If, in main.m you've got the following:

  void sortArray(NSMutableArray *a)
   {

   }

   int main( const int argc, char** argv )
   {

   }

Then I believe the correct terminology is that they're both C-style Function Calls. They persist in a C manner, not in an object-oriented manner like in C++, C#, or Java. You can even make C extern variables and functions, I think.

BUT

if you call

[array addObject:insert];

You're calling an Objective-C method (invoking a message, technically). Defined like the following.

@interface myClass : NSObject
{
    int myIvar;
}

+ (id) myStaticMethod: (NSObject *)parameter;
- (void) myInstanceMethod: (NSObject *)parameter;

@end

@implementation

+ (id) myStaticMethod: (NSObject *)parameter
{

}

- (void) myInstanceMethod: (NSObject *)parameter
{

}

@end

Hope that helps.

Stephen Furlani
  • 6,794
  • 4
  • 31
  • 60
3

main in Objective-C is exactly the same main in C or C++. A stand-alone function which is the entry point of the program. Some books may call it the main method because they are a little loose with the terminology.

Technically, Objective-C has methods, which are invoked in response to messages being sent to an object. C++ has member functions, which are called directly.

Ferruccio
  • 98,941
  • 38
  • 226
  • 299
-2

There is no difference between Function and Method, both are same. Some languages has some terminology. In C, it is called as function, In C++, it is called as member-function, in java, objective-c, it is called as method.