views:

103

answers:

3

Coming from a C++ background, one thing that confuses me about Objective C is the fact that you can add a method to a class without actually specifying it in the class interface. So I had a barrage of questions:

  1. Why would someone choose to not add the method in the class interface?
  2. Is it simply because of visibility?
  3. Methods without a declaration in the interface are private?
  4. Is declaring methods in a class interface just optional?
  5. Is it different for overriding a base class' method?
+2  A: 

I believe that this is the only way to create private methods in Objective-C. The language does not support the ability to declare a private method so by not declaring a method in the header file you are making private from all callers.

  1. Proper data encapsulation requires that you lock down access to members that either expose data or manipulates it. Not all members ought to be exposed.
  2. Yes it is.
  3. Yes, this is true.
  4. Yes, this is true as well.
  5. This I am not sure about - perhaps someone with more Objective-C knowledge could answer this one.
Andrew Hare
Note that methods not declared in the interface are still not truly "private": anyone can still call them at runtime (perhaps after using introspection to find all methods).
David Gelhar
@David - Good point but that is true even of languages that provide the ability to declare private members.
Andrew Hare
+4  A: 

The main difference is that C++ sets up much of its inheritance and types at compile time and Objective C does it mostly at runtime.

The only differences in putting a method in the interface (if all parameters are objects) in objective-C are that the compiler can see it at compile time and check that an object could respond to the method - if it does not then you get a warning but the compilation does succeed and the program will run and loo for the method at runtime. If the method is in the implementation of the class or a category (or some other way) then the run time will find it and call it successfully.

There are NO private methods you can call any method.

Mark
+1  A: 

Extending Andrew Hare's answer to answer 5, no, it doesn't: whether declared in an @interface or otherwise, method replacement/refinement works the same.

Frank Shearar