Private methods in a category using an anonymous category

I am creating a category over NSDate. It has some useful methods that should not be part of an open interface.

How can I make them private?

I try 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 does not work inside another category:

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

What is the best way to have private methods in a category?

+6
source share
4 answers

It should be like this:

 @interface NSDate () @end @implementation NSDate (NSDate_Comparing) @end 
+3
source

It should be

 @interface NSDate (NSDate_Comparing) 

as in @implementation . Regardless of whether you put @interface in your own .h file, it is up to you, but most of the time you would like to do this because you want to reuse this category in several other classes / files.

Make sure that the prefix of your own methods does not interfere with the existing method. or possible future enhancements.

+2
source

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

APIClient + SignupInit.h

 @interface APIClient (SignupInit) - (void)methodIAddedAsACategory; @end 

and then in APIClient + RegistrationInit.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 
+2
source

To avoid the warnings that other proposed solutions have, you can simply 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 
-1
source

Source: https://habr.com/ru/post/891350/


All Articles