Question

I was going through one of Apple's tutorial (your second iOS app). Basically, you have a primary data class and a data controller class. Controller class manipulates the primary data objects by creating an array that holds them.

Suddenly this pops up:

"...But the “create the master collection” task is a task that only the data controller object needs to know about. Because this method does not need to be exposed to other objects, you do not need to declare it in the header file."

And turns out the initialization of the "master collection" appears in the .m file as a class extension instead of the header file. Why do we want to do this? What's wrong with declaring the method of initialization within the header file directly?

Header file of the data controller:

#import <Foundation/Foundation.h>

@class BirdSighting;
@interface BirdsSightingDataController : NSObject

@property (nonatomic, copy) NSMutableArray *masterBirdSightingList;
- (NSUInteger)countOfList;
- (BirdSighting *)objectInListAtIndex:(NSUInteger)theIndex;
- (void)addBirdSightingWithName:(NSString *)inputBirdName location:(NSString *)inputLocation;

@end

this is the corresponding .m file:

#import "BirdsSightingDataController.h"
#import "BirdSighting.h"

@interface BirdsSightingDataController ()

- (void)initializeDefaultDataList; //class extension

@end

@implementation BirdsSightingDataController
...
Was it helpful?

Solution

Putting methods in an interface inside of a .m file is the proper way of making methods hidden.

-

There's nothing really "wrong" with declaring this method in the header file. You can do this if you want.

However, it's better practice to hide methods in your implementation file by using private header extensions if there's no need to make the method public. This means that if no other class needs to call this method, or if no other programmer needs to call this method, then it's better practice to keep the method private, or hidden.

A case like this will help explain the situation:

First, putting methods in a hidden interface extension in your .m files is a conscious decision. As another developer, if I am looking at your code and see that you have consciously decided to put a method in a hidden interface () in your implementation file, I will know that this method is used only in this class... and that YOU have done this on purpose.

Furthermore, it is good practice because if you are developing an API which is going to be used by other people, or working on the same code base with other developers, it limits their ability to call specific methods outside of the class itself. That means, they can't accidentally call the method from another object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top