开发者

Simple Objective-C question : why is main a method and not a function?

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 ma开发者_高级运维in 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?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜