5

My code looks like

- int add_two_numbers:(int)number1 secondnumber:(int)number2;

int main()
{
    return 0;
}

- int add_two_numbers:(int)number1 secondnumber:(int)number2
{
    return number1 + number2;
}

I got error saying "missing context for method declaration" and "expected method body". I am following the tutorials on tutorialpoints on objective-c, but it is very vague in this section. It seems like the methods have to be in some classes, and cannot go alone like what I did. What's going on?

return 0
  • 4,226
  • 6
  • 47
  • 72
  • 4
    That tutorial is doing an absolutely terrible job of teaching you about this. Functions exist in ObjC, distinctly from methods; they are related at a deeper level, but _not the same thing_. "Basically in Objective-C, we call the function as method" is nonsense. I would suggest finding another resource to learn from. Have a look at [Good resources for learning ObjC](http://stackoverflow.com/q/1374660) – jscs Jan 29 '16 at 19:30
  • 1
    you can directly call c's function from objective c. – Ratul Sharker Jan 29 '16 at 19:36
  • 2
    You could make that a normal C function: `int add_two_numbers(int number1, int number2)` – rmaddy Jan 29 '16 at 20:01
  • 1
    That tutorial is just flat out wrong in a number of places. I would recommend against using it for anything. – bbum Jan 30 '16 at 06:00

1 Answers1

5

Methods like the second one can only live in classes. You can use the C stand-alone syntax whenever you want a stand-alone function.

Also, your syntax is slightly off -- in a class, you'd declare it like this:

- (int)add_two_numbers:(int)number1 secondnumber:(int)number2
{
   return number1 + number2;
}

With the return type in parentheses.

Lou Franco
  • 87,846
  • 14
  • 132
  • 192
  • 2
    Except you shouldn't use '_' and it should be camel cased. I.e. `- (NSInteger) addNumberOne:(NSInteger)numberOne toSecondNumber:(NSInteger) numberTwo;` or the like. – bbum Jan 30 '16 at 03:52