0

My code compiles and returns the expected result even when my @interface section is blank, and I'm not sure why. Proper code:

@interface XYPoint : NSObject
-(void) setX: (int) x;
-(void) setY: (int) y;
-(int) valueX;
-(int) valueY;

@end

Code still compiles when @interface looks like this:

@interface XYPoint : NSObject

@end

Why does the code still work when I neglect to declare any methods in the @interface portion of a class section?

The full code block is at http://pastebin.com/J40gJbbj

2 Answers 2

4

Your code compiles when you removed the declarations from the .h file because no other classes must be using those methods.

Methods should only be declared in the .h file if they are intended to be used by other classes. They are not needed at all for the implementation of the actual class.

It sounds like you need to go back to many of your .h files and remove all unnecessary method declaration.

The only things that should appear in the .h are things for other classes to use. This includes instance variables (it's very rare to have public instance variables), properties, and methods. Many protocols that you add to the @interface line should also be moved to the .m file. All of your private ivars, properties, and protocol references should be added in the .m file.

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I needed. Thanks! This is one of the first exercises from a book, and I think they have me making these method declarations to introduce proper syntax.
1

Because the compiler is smart enough to find them in your implementation, which is why it compiled.

The reason it doesn't crash is in objective-c technically you can send any message to any object, it just might not respond to it. thats the power of the runtime.

In objective-c while we have types they aren't needed. You can use simple duck typing like so:

id obj = ...

if ( [myObj respondsToSelector:@selector(valueX)] )
{
  // myXYPoint talks like a XYPoint
   int aXval = [(XYPoint*)myobj valueX];

  //or if you don't like the cast,
  aXval = [myObj performSelector:@selector(valueX)];

}

2 Comments

To be fair, the types are absolutely needed, they just aren't enforced very carefully unlike some other languages.
It certainly is considered best practices, and i wouldn't write production code without them, but its not "needed".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.