Private Objective-C Classes

Guides | Tutorial By 6 years ago

If you code precompiled libraries for people to use (frameworks, static libraries etc) you may want to hide your variables from the headers so other coders know as little about how your classes work as possible. It works similar to categorising a class and adding new methods, except you can also use new variables that only the implementation file (.m) knows about.

To do so, at the top of your .m file simply create a category with an empty category name, inside this @interface add your variables, used protocols, properties and private methods.

Here is what many classes look like.

//	SomeClass.h

@interface SomeClass : NSObject 
{
	CGFloat someVariable;
	NSString* someOtherVariable;
}

@property (nonatomic, assign) id someDelegate;

- (void) doSomething;
- (NSArray*) doSomethingSecret;

@end
//	SomeClass.m

#import "SomeClass.h"

@implementation SomeClass

@synthesize someDelegate;

- (void) doSomething
{
	
}

- (NSArray*) doSomethingSecret
{
	return nil;
}

@end

Just taking the .h into account you can get some understanding of what the class is doing, and what it stores.

Everything that other classes don’t need to know about can be easily moved to the .m, like so:

//	SomeClass.h

@interface SomeClass : NSObject

- (void) doSomething;

@end
//	SomeClass.m

#import "SomeClass.h"

@interface SomeClass () 
{
	CGFloat someVariable;
	NSString* someOtherVariable;
}

@property (nonatomic, assign) id someDelegate;

- (NSArray*) doSomethingSecret;

@end

@implementation SomeClass

@synthesize someDelegate;

- (void) doSomething
{
	
}

- (NSArray*) doSomethingSecret
{
	return nil;
}

@end

Now only one method is public.