Pranit Kothari
Pranit Kothari

Reputation: 9841

Do I need to declare a method prior to the first use of the method in same class?

I am new in Objective C, and working in C/C++ till now.

In C/C++, if function do not know prototype of function, it will not call that function, even if it is in same file. So we either use header file, or write prototype before using it. Like,

void proto(void);

void somefun()
{
   proto(); //call the function 
}

But in Objective C, I have function in same file, but I can call it without giving its prototype. Following is code which is compiling correctly.

//calling before actually declaring/defining, but works fine.
[self processResponse:responseObject]; 

-(void)processResponse:(id)responseObject
{

}

Can Objective C calls functions without knowing prototype if it is in same class? What should I prefer?

Please note that processResponse is internal function. I do not want it to expose it to any other class.

Upvotes: 1

Views: 157

Answers (3)

Freedom
Freedom

Reputation: 212

Just like in C in Objective-C you have to declare a function before using it. What you are doing in your example is not calling function before declaring it but sending a message (or invoking a method if we want to use a more OOP terminology) to an object. Which is a different thing. Anyway for all the versions of the LLVM compiler included in Xcode starting from version 4.3 the order of methods declaration doesn't matter anymore since if the compiler encounter a not yet declared method it will look in the rest of the @implementation block to see if it has been declared later.

Upvotes: 0

Matic Oblak
Matic Oblak

Reputation: 16774

You are comparing functions with methods. Functions still have same rules as in C. As for objective C methods there are no prototypes. You may declare the method in header or as a class extension but those make them public. As for protected methods you do not need anything, just create the method and call it from anywhere inside the class.

It used to be that you had to put these privet methods on top of the class to use them (method B could call method A only if method A was written above the method B) but that was a long time ago.

Upvotes: 1

Can Objective C calls functions without knowing prototype if it is in same class?

Yes it will try to call it.

What should I prefer?

It is better to declare the function in private extention part of the implementation file(.m) since you dont want to expose that function to other class.

Advandtages:

1.Other Peer can understand the method only as internal

2.Other than that class, no one can access it.

in Implementation file(.m)

@interface MyClass ()

-(void)processResponse:(id)responseObject;

@end

@implementation MyClass

@end

Upvotes: 1

Related Questions