bastibe
bastibe

Reputation: 17199

Is it good practice to put private API in the .m files and public API in .h files in Cocoa?

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

Answers (2)

Barry Wark
Barry Wark

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

Dietrich Epp
Dietrich Epp

Reputation: 213378

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

Upvotes: 5

Related Questions