When do you create initialization methods in .m files with a class extension?

I went through one of the Apple tutorials (second iOS app). Basically, you have a primary data class and a data controller class. The controller class manages the primary data objects, creating an array that holds them.

Suddenly this pops up:

"... But the task of" creating the main collection "is a task that only the data controller object needs to know about. Since this method does not need to be exposed to other objects, you do not need to declare it in the header file."

And it turns out that the initialization of the "main collection" appears in the .m file as an extension of the class instead of the header file. Why do we want to do this? What is wrong with declaring the initialization method inside the header file directly?

Data controller header file:

#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
...
+3
source share
1 answer

Using methods in an interface inside a .m file is the right way to create methods hidden.

-

There is nothing really “wrong” with declaring this method in the header file. You can do this if you want.

However, it is better to hide the methods in your implementation file using private header extensions if you do not need to publish this method. This means that if no other class should call this method, or if another programmer does not need to call this method, it is better to use this method for a private or hidden method.

A similar case will help explain the situation:

-, .m . , , () , , ... .

, , , API, , , , .

+2

All Articles