Reputation: 17199
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.
Upvotes: 2
Views: 301
Reputation: 107754
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.
Upvotes: 6