views:

108

answers:

2

Many of my classes in my current project have several properties and methods that are only ever called from within the class itself. Also, they might mess with the working of the class depending on the current state of the class.
Currently, all these interfaces are defined in the main interface declaration in the .h files. Is it considered good practice to put the “private” methods and properties at the top of the .m files?

This won't ever affect anything since I am very likely the only person ever to look at this source code, but of course it would be interesting to know for future projects.

+5  A: 

Yes, put them in a category at the top of your .m files.

Dietrich Epp
If you're using Objective-C 2.0, use a class extension rather than a category in your .m file.
Barry Wark
+6  A: 

Starting with Objective-C 2.0, the best practice is to put private methods in a "class extension". This allows the compiler to warn you if you haven't implemented one of the methods. Class extensions also let you modify the read/write semantics of @properties so that the public API can, for example, specificy readonly for a property while internally the property can be used as readwrite.

In .h:

@interface MyClass : NSObject
{}

@property (readonly) id myProp;

- (void)aPublicMethod;
@end

In .m:

@interface MyClass ()
@property (readwrite) id myProp; //upgrade myProp to readwrite within the class.

- (id)aPrivateMethod;
@end

@implementation MyClass
@synthesize myProp;

- (void)aPublicMethod { ... }

- (id)aPrivateMethod;

@end

If you forget to implement -aPrivateMethod within the main @implementation block, the compiler will give a warning. This is better than the old way of using a category like @interface MyClass (PrivateMethods) in which case, the compiler couldn't warn you that the method wasn't implemented.

Barry Wark
A class extension is the way to go. IIRC the extension methods _have_ to be defined in the main @implementation block. If you use a named category then it can go in the main @implementation block, or a separate block in the same or a different .m file.
Abizern
@Abizem is exactly right. That's why the compiler won't/can't warn you if you forget to implement a method in a named category; the implementation could be *anywhere* or even added at runtime.
Barry Wark