cfischer
cfischer

Reputation: 24892

Private methods in a Category, using an anonymous category

I'm creating a category over NSDate. It has some utility methods, that shouldn't be part of the public interface.

How can I make them private?

I tend to use the "anonymous category" trick when creating private methods in a class:

@interface Foo()
@property(readwrite, copy) NSString *bar;
- (void) superSecretInternalSaucing;
@end

@implementation Foo
@synthesize bar;
.... must implement the two methods or compiler will warn ....
@end

but it doesn't seem to work inside another Category:

@interface NSDate_Comparing() // This won't work at all
@end

@implementation NSDate (NSDate_Comparing)

@end

What's the best way to have private methods in a Category?

Upvotes: 7

Views: 3913

Answers (4)

Pwner
Pwner

Reputation: 3785

To avoid the warnings that the other proposed solutions have, you can just define the function but not declare it:

@interface NSSomeClass (someCategory) 
- (someType)someFunction;
@end

@implementation NSSomeClass (someCategory)

- (someType)someFunction
{
    return something + [self privateFunction];
}

#pragma mark Private

- (someType)privateFunction
{
    return someValue;
}

@end

Upvotes: -1

Michał Zygar
Michał Zygar

Reputation: 4092

I think the best way is to make another category in .m file. Example below:

APIClient+SignupInit.h

@interface APIClient (SignupInit)

- (void)methodIAddedAsACategory;
@end

and then in APIClient+SignupInit.m

@interface APIClient (SignupInit_Internal)
- (NSMutableURLRequest*)createRequestForMyMethod;
@end

@implementation APIClient (SignupInit)

- (void)methodIAddedAsACategory
{
    //category method impl goes here
}
@end

@implementation APIClient (SignupInit_Internal)
- (NSMutableURLRequest*)createRequestForMyMethod
{
    //private/helper method impl goes here
}

@end

Upvotes: 2

Paul Semionov
Paul Semionov

Reputation: 491

It should be like this:

@interface NSDate ()

@end

@implementation NSDate (NSDate_Comparing)

@end

Upvotes: 4

Eiko
Eiko

Reputation: 25632

It should be

@interface NSDate (NSDate_Comparing)

as in the @implementation. Whether or not you put the @interface in its own .h file is up to you, but most of the time you'd like to do this - as you want to reuse that category in several other classes/files.

Make sure to prefix your own methods to not interfere with existing method. or possible future enhancements.

Upvotes: 2

Related Questions