Private Objective-C Classes

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 <UITableViewDelegate>
{
	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 () <UITableViewDelegate>
{
	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.

This entry was posted in How to guides, Tutorial and tagged , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">